0% found this document useful (0 votes)
3 views

unit 5 python

This document provides a comprehensive guide on connecting Python with MySQL databases, including installation, creating connections, and executing various SQL commands such as creating databases, tables, inserting records, and querying data. It also covers important operations like updating, deleting records, and managing transactions with commit and rollback methods. Additionally, it emphasizes the importance of closing database connections after operations are complete.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

unit 5 python

This document provides a comprehensive guide on connecting Python with MySQL databases, including installation, creating connections, and executing various SQL commands such as creating databases, tables, inserting records, and querying data. It also covers important operations like updating, deleting records, and managing transactions with commit and rollback methods. Additionally, it emphasizes the importance of closing database connections after operations are complete.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT 5: CONNECTING WITH

DATABASE

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 1

Python MySQL
Python can be used in database applications. One of the most popular databases is MySQL.

MySQL dB Interface Installation


Python needs a MySQL driver to access the MySQL database. Navigate your command line to
the location of PIP, and type the following:
python -m pip install mysql-connector-python

Create Connection
Start by creating a connection to the database. Use the username and password from your
MySQL database:
Example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=" "
)
print(mydb)

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It
facilitates us to have multiple separate working environments through the same connection to the
database. We can create the cursor object by calling the 'cursor' function of the connection object.
The cursor object is an important aspect of executing queries to the databases.

Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=" "
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

Getting the list of existing databases


You can check if a database exists by listing all databases in your system by using the "SHOW
DATABASES" statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=" "

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 2

)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)

Or you can try to access the database when making the connection:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=" "
database=”mydatabase”
)

Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.
Make sure you define the name of the database when you create the connection
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE students(rno INT(3),name VARCHAR(255), class
VARCHAR(10), college VARCHAR(50))")

Check if Table Exists


You can check if a table exist by listing all tables in your database with the "SHOW TABLES"
statement:
Example
Return a list of your system's databases:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 3

for x in mycursor:
print(x)

Primary Key
When creating a table, you should also create a column with a unique key for each record.
This can be done by defining a PRIMARY KEY.
We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique
number for each record. Starting at 1, and increased by one for each record.
Example
Create primary key when creating the table:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE students(rno INT AUTO_INCREMENT PRIMARY


KEY,name VARCHAR(255), class VARCHAR(10), college VARCHAR(50))")

If the table already exists, use the ALTER TABLE keyword:


Example
Create primary key on an existing table:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE students ADD constraint AUTO_INCREMENT PRIMARY


KEY(rno)")

Insert Into Table


We can insert the record by using Insert statement.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 4

database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO students (name, class, college) VALUES (%s, %s, %s)"
val = ("Kevin sunny", "bca6","christ")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

User input to insert the record


Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
nm=input("enter name:")
cls=input("enter class:")
clg=input("enter college:")
sql = "INSERT INTO students (name, class, college) VALUES (%s, %s, %s)"
val = (nm,cls,clg)
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Insert multiple rows


We can also insert multiple rows at once using the python script. The multiple rows are
mentioned as the list of various tuples.
To insert multiple rows into a table, use the executemany() method.
The second parameter of the executemany() method is a list of tuples, containing the data you
want to insert. Each element of the list is treated as one particular row, whereas each element of
the tuple is treated as one particular column value (attribute).
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO students (name, class, college) VALUES (%s, %s, %s)"

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 5

val = [("meet","bca4","marwadi"),("richa","bca2","christ"),("harsh","bca2","atmiya")]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

Get Inserted Row ID


You can get the id of the row you just inserted by asking the cursor object. In SQL, a particular
row is represented by an insertion id which is known as row id. We can get the last inserted row
id by using the attribute lastrowid of the cursor object.
Note: If you insert more than one row, the id of the last inserted row is returned.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO students (name, class, college) VALUES (%s, %s, %s)"
val = ("riya","bca6","christ")
mycursor.execute(sql, val)

mydb.commit()

print("1 record inserted, ID:", mycursor.lastrowid)

Select From a Table


To select from a table in MySQL, use the "SELECT" statement. The SELECT statement is used
to read the values from the databases. We can restrict the output of a select query by using
various clause in SQL like where, limit, etc.
Python provides the fetchall() method returns the data stored inside the table in the form of rows.
We can iterate the result to get the individual rows.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM students")

myresult = mycursor.fetchall()
for x in myresult:
print(x)

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 6

Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the
column name(s).
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT rno,name FROM students")

myresult = mycursor.fetchall()

for x in myresult:
print(x)

The fetchone() method


The fetchone() method is used to fetch only one row from the table. The fetchone() method
returns the first row of the result-set.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM students")

myresult = mycursor.fetchone()

print(myresult)

Formatting the result


We can format the result by iterating over the result produced by the fetchall() or fetchone()
method of cursor object.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 7

mycursor.execute("SELECT * FROM students")

myresult = mycursor.fetchall()

print("Rno \t Name \t Class \t College")


for x in myresult:
print("%d\t %s \t %s \t %s"%(x[0],x[1],x[2],x[3]))

mydb.close()

Using where clause


We can restrict the result produced by the select statement by using the where clause. This will
extract only those columns which satisfy the where condition.
Example: printing the records whose names starts with “r”
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM students where name like 'r%'")

myresult = mycursor.fetchall()

print("Rno \t Name \t Class \t College")


for x in myresult:
print("%d\t %s \t %s \t %s"%(x[0],x[1],x[2],x[3]))

mydb.close()

Example: printing the records with rno = 1, 2, and 3


mycursor.execute("SELECT * FROM students where rno in (1,2,3)")

Example: printing name and college with class=’bca6’


import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name,college FROM students where class='bca6'")

myresult = mycursor.fetchall()

print("Name \t College")

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 8

for x in myresult:
print("%s \t %s"%(x[0],x[1]))

mydb.close()

Sort the Result


Use the ORDER BY statement to sort the result in ascending or descending order.
The ORDER BY keyword sorts the result ascending by default. To sort the result in descending
order, use the DESC keyword.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM students order by name ")

myresult = mycursor.fetchall()

print("Rno \t Name \t Class \t College")


for x in myresult:
print("%d \t %s \t %s \t %s"%(x[0],x[1],x[2],x[3]))

mydb.close()

ORDER BY DESC
mycursor.execute("SELECT * FROM students order by name DESC ")

Update Table
The UPDATE-SET statement is used to update any record inside the table.
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("UPDATE students SET class='bca6' WHERE rno=1")

mycursor.execute("SELECT * FROM students")

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 9

myresult = mycursor.fetchall()

print("Rno \t Name \t Class \t College")


for x in myresult:
print("%d \t %s \t %s \t %s"%(x[0],x[1],x[2],x[3]))

mydb.close()

Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement. Here,
we must impose a condition using WHERE clause otherwise all the records from the table will
be removed.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("DELETE from students WHERE rno=1")
print(mycursor.rowcount, "record(s) deleted")

mycursor.execute("SELECT * FROM students")

myresult = mycursor.fetchall()

print("Rno \t Name \t Class \t College")


for x in myresult:
print("%d \t %s \t %s \t %s"%(x[0],x[1],x[2],x[3]))

mydb.commit()
mydb.close()

Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.

Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement.
Example
Create a temporary table
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 10

password="",
database="mydatabase"
)
mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address


VARCHAR(255))")

Delete the above table


import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
mycursor = mydb.cursor()

mycursor.execute("DROP table customers")

mycursor.execute("SHOW TABLES")

for x in mycursor:
print(x)

Drop Only if Exist


If the the table you want to delete is already deleted, or for any other reason does not exist, you
can use the IF EXISTS keyword to avoid getting an error.

mycursor.execute("DROP TABLE IF EXISTS customers")

MySQL Limit
You can limit the number of records returned from the query, by using the "LIMIT" statement.
Example
Select the 3 first records in the "students" table.
mycursor.execute("SELECT * FROM customers LIMIT 3")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Start From Another Position


If you want to return five records, starting from the third record, you can use the "OFFSET"
keyword.
Example
Start from position 3, and return 5 records
mycursor.execute("SELECT * FROM students LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 11

for x in myresult:
print(x)

Python commit() method


Python provides the commit() method which ensures the changes made to the database
consistently take place.
The syntax to use the commit() method is given below
mydb.commit()

All the operations that modify the records of the database do not take place until the commit() is
called.

Python rollback() method


The rollback() method is used to revert the changes that are done to the database. This method is
useful in the sense that, if some error occurs during the database operations, we can rollback that
transaction to maintain the database consistency.
The syntax to use the rollback() is given below.

mydb.rollback()

Closing the connection


We need to close the database connection once we have done all the operations regarding the
database. Python provides the close() method. The syntax to use the close() method is given
below.

mydb.close()

Compiled by: Kruti Kotak, Christ College, Rajkot

You might also like