0% found this document useful (0 votes)
57 views7 pages

Interface Python With SQL Database

The document provides a comprehensive guide on interfacing Python with SQL databases, specifically MySQL, detailing the steps for establishing connectivity, executing SQL queries, and managing data. It covers installation of the mysql-connector-python package, creating and manipulating databases and tables, and performing CRUD operations using Python scripts. Additionally, it explains the importance of committing transactions and closing connections to manage resources effectively.

Uploaded by

foodprog68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views7 pages

Interface Python With SQL Database

The document provides a comprehensive guide on interfacing Python with SQL databases, specifically MySQL, detailing the steps for establishing connectivity, executing SQL queries, and managing data. It covers installation of the mysql-connector-python package, creating and manipulating databases and tables, and performing CRUD operations using Python scripts. Additionally, it explains the importance of committing transactions and closing connections to manage resources effectively.

Uploaded by

foodprog68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Interface Python with SQL database

Contents:
 Connecting SQL with Python
 Creating database connectivity applications
 Performing insert, delete, update,delete 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.
 Mysql.connector- Library or package to connect from python to MySQL.

Before we connect the program with mysql , we need to install connectivity package named
mysql-connector- python
 Command to install connectivity package:- pip install mysql-connector-python

 Command to import connector:- import mysql.connector

 Steps for python MySQL connectivity

1 . Install Python
2. Install MySQL

3. Open Command prompt

4. Switch on internet connection

5. Type pip install mysql-connector-python and execute

6. Open python IDLE

7. import mysql.connector

Steps for creating database connectivity applications:

1.Start Python- start python editor to create our own python script.

2.Import mysql.connector package

Use the following statement for this.


import mysql.connector

or

import mysql.connector as con

3.Establishing a connection to Mysql DATABASE.

We need to establish a connection to a mysql database using connect () function of


mysql.connector package.

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>)

For eg: import mysql.connector


con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”
“)
4. 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()

5. Execute SQL query:


We can execute SQL query using execute() function

.Syntax: <cursor object>.execute(SQL

QUERY) Eg: cursor.execute(“select * from

data”)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.

6.Extract data from Result set:

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()

 Multiple 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.
7.Functions to execute SQL queries

# TO CREATE DATABASE SCHOOL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m")
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)

# TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE

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,NAMEVARCHAR(20),AMOUNT INT);")

# TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW
TABLES")
for x in mycursor:
print(x)
#TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE

mydb=mysql.connector.connect(host="localhost",user="root",passwd="system"
,database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC
STUDENT")
for x in mycursor:
print(x)
# TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE

import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="1234
5",database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()

# TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON


INTERFACE
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345
",database="student")
if conn.is_connected()==False:
print("Error connecting to MYSQL
DATABASE")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of ows:",count)
for row in r:
print(row)
#TO INSERT A RECORD (ROLLNO,NAME,AND MARKS) IN MYSQL TABLE
student USING#PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")

mycursor=mydb.cursor()
r=int(input("enter the
rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO
student(rollno,name,marks)
VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD
INSERTED")

# TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syst
em",database="student")

mycursor=mydb.cursor()

mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE


MARKS=40")
mydb.commit()
print(mycursor.rowcount,"RECORD
UPDATED")
# TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM STUDENT WHERE
MARKS<50")
mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")

# TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON


INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE
STUDENT")

# TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD
AGE INT”)
mydb.commit()
#TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE DROP
AGE ”)
mydb.commit()

# TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
 commit( ): After executing insert or update query we must
commit ourtransaction using commit method of connection
object.
Eg: mycon.commit()
 rollback( ): mysqlConnection.rollback() reverts the changes
made by thecurrent transaction.
 rowcount: This attribute returns the number of rows that were
affectedby an execute()

Closing cursor and connection


Since the database can keep limited number of
connections at a time ,we must close the connection
using cursorobject.close()
Eg: mycursor.close()
con.close()

You might also like