pythonmysqlnew
pythonmysqlnew
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”)
host:- It represents IP address of database server. If database is available on local machine
then it will be “localhost” or “127.0.0.1”
user:- In mysql its default value is always “root”.
password:- is the password that was specified at time of MYSQL installation
database:- is the name of database created in MYSQL, if created.
We can use is_connected() to verify that the connection with mysql is successful.
For example:
if connectionobject.is_connected():
print(‘Successful connection’)
And then perform the remaining task only if the connection is successfully established.
“A database connection object controls the connection to the database. It represents a
unique session with a database connected from within a program/script.”
E-SCHOOL
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()
cur=con.cursor()
cmd="create database SMS"
cur.execute(cmd)
con.commit()
con.close()
If not sure that the database exists or not, then SQL command can be given as
cmd="create database if not exists SMS"
For String and date values {} must be used within ‘ ’ and date should be entered as
yyyy-mm-dd
E-SCHOOL
con.close()
OUTPUT
[(101, 'Aman Kapoor', 99.0), (102, 'Raka', 78.0), (106, 'Billu', 99.0)]
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"
E-SCHOOL
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)
E-SCHOOL
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)