Python MySQL Connectivity Notes
Python MySQL Connectivity Notes
The connect statement creates a connection to the mysql server and returns a MySQL
connection object.
Syntax:
<Connection object>=mysql.connector.connect (host=<hostname>, user=<username>,
passwd <password>, database=<dbname>)
----------------
import mysql.connector
con=mysql.connector.connect(host=”localhost”, user=”root”, passwd=” “)
-----------------
Creating a cursor Object:
It is a useful control structure of database connectivity. It will let us execute all the queries
we need. Cursor stores all the data as a temporary container of returned data and allows
traversal so that we can fetch data one row at a time from cursor. Cursors are created by
the connection.cursor() method.
Syntax:
<cursor object>=<connectionobject> .cursor()
Eg: Cursor=con.cursor()
--------------------
The above code will execute the sql query and store the retrieved records (resultset) in the
cursor object(cursor).
Result set refers to a logical set of records that are fetched from the database by executing
an sql query and made available in the program.
-------------
The records retrieved from the database using SQL select query has to be extracted as
record from the result set. We can extract data from the result set using the following
fetch() function.
fetchall()
fetchone()
fetchmany()
-----
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”, user=”root”, passwd=”system”)
mycursor=mydb.cursor()
mycursor.execute(“Create Database School”)
Show database
import mysql.connector
mydb=mysql.connector.connect(host=”localhost” ,user=”root”, passwd=”system”)
mycursor=mydb.cursor()
mycursor.execute(“Show Databases”)
for x in mycursor:
print (x)
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”, user=”root”, passwd=”system”,
database=”student”)
mycursor=mydb.cursor()
mycursor.execute(“Create Table Fees (Rollno Int, Name Varchar(20), Amount Int)”)
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”system”,
database=”student”)
mycursor.execute (“Show tables”)
for x in mycursor:
print (x)
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”system”,
database=”student”)
mycursor.execute (“Desc Student”)
for x in mycursor:
print (x)
import mysql.connector
mydb=mysql.connector.connect (host=”localhost”,user=”root”, passwd=”system”,
database=”student”)
c= mydb.cursor()
c.execute (“select* from student”)
r=c.fetchone()
while r is none :
print (r)
r=c.fetchone()