Page 2 - Interface Python With SQL
P. 2
is_connected()
will check whether the connection is successful or not, returns True/False
Ex.
if mydb.is_connected():
print("Successful connection")
Creating a cursor instance/object
It is the database object which send query to the server for execution, the server sends the resultset
of the query in one burst, cursor allows to traverse the result set row by row.
A resultset is an object that is returned when a cursor object is used to query a table.
Ex.
mycursor=mydb.cursor()
Execute SQL query
Execute function of created database object/cursor sends the sql command to server and fetches
the result back into the cursor.
Ex:
mycursor.execute("show databases")
(mycursor is the cursor created in the program)
1) Program to display list of all the databases.
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", passwd="1234")
mycursor=mydb.cursor()
mycursor.execute("show databases")
for db in mycursor:
print(db)
2) Program to create database
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", passwd="1234")
mycursor=mydb.cursor()
mycursor.execute("create database SCHOOL")
3) Program to create table in an existing database.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="1234",\
database="school")
mycursor=mydb.cursor()