Interface Python With SQL Database Notes
Interface Python With SQL Database Notes
Contents:
♦ Connecting SQL with Python
♦ Creating database connectivity application
♦ Performing insert, delete, update, queries
♦ Display data by using fetchone(), fetchall(),fetchmany(), rowcount()
Database connectivity
Database connectivity refers to connection and communication between an
application and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server
application and database that work behind the scenes to deliver information to the
user.
The connect statement creates a connection to the MySQL server and returns a
MySQL connection object.
Syntax:
Syntax:
Eg: Cursor=con.cursor()
Syntax:
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.
fetchall()
fetchone()
fetchmany()
Ways to retrieve data
fetchall()-Fetches all (remaining) rows of a query result. returning them as a
sequence of sequences (e.g. a list of tuples).
fetchone()-Fetches the next row of a query result set, returning a single sequence or
None when no more data is available
fetchmany (size)-Fetches the next set of rows of a query result, returning a sequence
of sequences. It will return number of rows that matches to the size argument.
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)
for x in mycursor:
print (x)
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”system”,
database=”student”)
c= mydb.cursor()
r=c.fetchone()
while r is none :
print (r)
r=c.fetchone()