Python MYSQL
Python MYSQL
Environment Setup
To build the real world applications, connecting with the databases is the necessity for
the programming languages. However, python allows us to connect our application to
the databases like MySQL, SQLite, MongoDB, and many others.
In this section of the tutorial, we will discuss Python - MySQL connectivity, and we will
perform the database operations in python. We will also cover the Python connectivity
with the databases like MongoDB and SQLite later in this tutorial.
Install mysql.connector
To connect the python application with the MySQL database, we must import the
mysql.connector module in the program.
The mysql.connector is not a built-in module that comes with the python installation. We
need to install it to get it working.
https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09
f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz to download the
source code.
3. Open the terminal (CMD for windows) and change the present working directory to
the source code directory.
1. $ cd mysql-connector-python-8.0.13/
4. Run the file named setup.py with python (python3 in case you have also installed
python 2) with the parameter build.
Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application
to the database.
There are the following steps to connect a python application to our database.
Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google"
)
5.
6. #printing the connection object
7. print(myconn)
Output:
Here, we must notice that we can specify the database name in the connect() method if
we want to connect to a specific database.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "mydb")
5.
6. #printing the connection object
7. print(myconn)
Output:
1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
10.
11. print(cur)
Output:
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google"
)
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. dbs = cur.execute("show databases")
11. except:
12. myconn.rollback()
13. for x in cur:
14. print(x)
15. myconn.close()
Output:
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google"
)
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #creating a new database
11. cur.execute("create database PythonDB2")
12.
13. #getting the list of all the databases which will now include the new database Python
DB
14. dbs = cur.execute("show databases")
15.
16. except:
17. myconn.rollback()
18.
19. for x in cur:
20. print(x)
21.
22. myconn.close()
Output:
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
We can create the new table by using the CREATE TABLE statement of SQL. In our
database PythonDB, the table Employee will have the four columns, i.e., name, id,
salary, and department_id initially.
1. > create table Employee (name varchar(20) not null, id int primary key, salary float no
t null, Dept_Id int not null)
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Creating a table with name Employee having four columns i.e., name, id, salary, and
department id
11. dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not n
ull primary key, salary float not null, Dept_id int not null)")
12. except:
13. myconn.rollback()
14.
15. myconn.close()
Now, we may check that the table Employee is present in the database.
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table
schema. The alter statement used to alter the table schema if required. Here, we will
add the column branch_name to the table Employee. The following SQL query is used for
this purpose.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #adding a column branch name to the table Employee
11. cur.execute("alter table Employee add branch_name varchar(20) not null")
12. except:
13. myconn.rollback()
14.
15. myconn.close()
next →← prev
Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can
mention the format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of the
cursor.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goog
le",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
7.
8. #The row values are provided in the form of tuple
9. val = ("John", 110, 25000.00, 201, "Newyork")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. except:
19. myconn.rollback()
20.
21. print(cur.rowcount,"record inserted!")
22. myconn.close()
Output:
1 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.
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
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goog
le",database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
9. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of
spain"),("Nick",104,90000.00,201,"Newyork")]
10.
11. try:
12. #inserting the values into the table
13. cur.executemany(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17. print(cur.rowcount,"records inserted!")
18.
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:
3 records inserted!
Row ID
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.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goog
le",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6.
7. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
8.
9. val = ("Mike",105,28000,202,"Guyana")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. #getting rowid
19. print(cur.rowcount,"record inserted! id:",cur.lastrowid)
20.
21. except:
22. myconn.rollback()
23.
24. myconn.close()
Output:
Read Operation
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.
In this section of the tutorial, we will extract the data from the database by using the
python script. We will also format the output to print it on the console.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select * from Employee")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15. #printing the result
16.
17. for x in result:
18. print(x);
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:
In the following example, we will read the name, id, and salary from the Employee table
and print it on the console.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
9.
10. #fetching the rows from the cursor object
11. result = cur.fetchall()
12. #printing the result
13. for x in result:
14. print(x);
15. except:
16. myconn.rollback()
17. myconn.close()
Output:
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee")
12.
13. #fetching the first row from the cursor object
14. result = cur.fetchone()
15.
16. #printing the result
17. print(result)
18.
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10.
11. #Reading the Employee data
12. cur.execute("select name, id, salary from Employee")
13.
14. #fetching the rows from the cursor object
15. result = cur.fetchall()
16.
17. print("Name id Salary");
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000
Output:
Name id Salary
John 101 25000
John 102 25000
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 2500
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:
Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
This orders the result in the decreasing order of a particular column.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name desc")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. #printing the result
17. print("Name id Salary");
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20.
21. except:
22. myconn.rollback()
23.
24. myconn.close()
Output:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following
SQL query is used to update a column.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #updating the name of the employee whose id is 110
11. cur.execute("update Employee set name = 'alex' where id = 110")
12. myconn.commit()
13. except:
14.
15. myconn.rollback()
16.
17. myconn.close()
Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here, we
must impose a condition using WHERE clause otherwise all the records from the table
will be removed.
The following SQL query is used to delete the employee detail whose id is 110 from the
table.
Join Operation
We can combine the columns from two or more tables by using some common column
among them by using the join statement.
We have only one table in our database, let's create one more table Departments with
two columns department_id and department_name.
1. create table Departments (Dept_id int(20) primary key not null, Dept_Name varchar(20
) not null);
As we have created a new table Departments as shown in the above image. However,
we haven't yet inserted any value inside it.
Let's insert some Departments ids and departments names so that we can map this to
our Employee table.
Let's look at the values inserted in each of the tables. Consider the following image.
Now, let's create a python script that joins the two tables on the common column, i.e.,
dept_id.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #joining the two tables on departments_id
11. cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dep
t_id, Departments.Dept_Name from Departments join Employee on Departments.Dept_i
d = Employee.Dept_id")
12. print("ID Name Salary Dept_Id Dept_Name")
13. for row in cur:
14. print("%d %s %d %d %s"%(row[0], row[1],row[2],row[3],row[4]))
15.
16. except:
17. myconn.rollback()
18.
19. myconn.close()
Output:
Right Join
Right join shows all the columns of the right-hand side table as we have two tables in
the database PythonDB, i.e., Departments and Employee. We do not have any Employee
in the table who is not working for any department (Employee for which department id is
null). However, to understand the concept of right join let's create the one.
This will insert an employee Alex who doesn't work for any department (department id is
null).
Now, we have an employee in the Employee table whose department id is not present in
the Departments table. Let's perform the right join on the two tables now.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #joining the two tables on departments_id
11. result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departm
ents.Dept_id, Departments.Dept_Name from Departments right join Employee on Depart
ments.Dept_id = Employee.Dept_id")
12.
13. print("ID Name Salary Dept_Id Dept_Name")
14.
15. for row in cur:
16. print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
17.
18.
19.
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:
Left Join
The left join covers all the data from the left-hand side table. It has just opposite effect
to the right join. Consider the following example.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #joining the two tables on departments_id
11. result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departm
ents.Dept_id, Departments.Dept_Name from Departments left join Employee on Depart
ments.Dept_id = Employee.Dept_id")
12. print("ID Name Salary Dept_Id Dept_Name")
13. for row in cur:
14. print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
15.
16.
17.
18. except:
19. myconn.rollback()
20.
21. myconn.close()
Output:
Performing Transactions
Transactions ensure the data consistency of the database. We have to make sure that
more than one applications must not modify the records while performing the database
operations. The transactions have the following properties.
1. Atomicity
Either the transaction completes, or nothing happens. If a transaction contains 4
queries then all these queries must be executed, or none of them must be
executed.
2. Consistency
The database must be consistent before the transaction starts and the database
must also be consistent after the transaction is completed.
3. Isolation
Intermediate results of a transaction are not visible outside the current
transaction.
4. Durability
Once a transaction was committed, the effects are persistent, even after a system
failure.
Python commit() method
Python provides the commit() method which ensures the changes made to
All the operations that modify the records of the database do not take place until the
commit() is called.
1. Conn.rollback()
1. conn.close()
In the following example, we are deleting all the employees who are working for the CS
department.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goo
gle",database = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. cur.execute("delete from Employee where Dept_id = 201")
11. myconn.commit()
12. print("Deleted !")
13. except:
14. print("Can't delete !")
15. myconn.rollback()
16.
17. myconn.close()
Output:
Deleted !