Python Database
Python Database
MYSQL Installer
To connect Python with MYSQL we need to install MYSQL Connector and to do so, we
need to type the following command in command prompt:
pip install mysql-connector-python
Open a Connection
connect() is used to open a connection to a MYSQL database in python.
Syntax:-
<connectionobject> = msc.connect(host=”localhost”,user=”root”,
password=”sqlpassword”, database=”databasename”)
or
<connectionobject> = msc.connect(“localhost”,”root”,”password”,”dbname”)
Using commit()
commit() is used to save data in a Table, after insertion, modification or deletion.
Syntax:-
connectionobject.commit()
Closing a Connection
When we open a connection, then we must also clear the environment using close().
Syntax:-
connectionobject.close()
Python program to display all records one by one from Table Students
import mysql.connector as msc
con=msc.connect(host="localhost",user="root",passwd="India@123",database="grmxii")
cur=con.cursor()
cmd="select * from students"
cur.execute(cmd)
records=cur.fetchall()
for row in records:
for cols in row:
print(cols,end="\t")
print()
con.close()
OUTPUT
101 Aman Kapoor 99.0
102 Raka 78.0
106 Billu 99.0
OUTPUT
Total records:- 3
Parameterised Queries
There are two methods of using parameterized query.
Old method
In this method we write a command in following way:
r=int(input("Enter Rno"))
n=input("Enter Name")
cmd="select * from students where rno=%s or name='%s' " % (r,n)
Note: For string values %s is enclosed within single quotes (‘ ‘).
New method
In this method we write a command in following way:
r=int(input("Enter Rno"))
n=input("Enter Name")
cmd="select * from students where rno={} or name='{}’ ".format(r,n)