You are on page 1of 5

Python MySQL

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

Download MySQL Connector


import mysql.connector

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except
blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.

These exceptions can be handled using the try statement:

Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special
block of code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else
You can use the else keyword to define a block of code to be executed if no errors were
raised:
Example
In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally
The finally block, if specified, will be executed regardless if the try block raises an error or
not.

Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

READ Operation
READ Operation on any database means to fetch some useful information from the database.
Once our database connection is established, you are ready to make a query into this database. You
can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values
from a database table.
 fetchone() − It fetches the next row of a query result set. A result set is an object that is returned
when a cursor object is used to query a table.
 fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from
the result set, then it retrieves the remaining rows from the result set.
 rowcount − This is a read-only attribute and returns the number of rows that were affected by
an execute() method.

Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following four
properties −
 Atomicity − Either a transaction completes or nothing happens at all.
 Consistency − A transaction must start in a consistent state and leave the system in a
consistent state.
 Isolation − Intermediate results of a transaction are not visible outside the current transaction.
 Durability − Once a transaction was committed, the effects are persistent, even after a system
failure.

COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the changes, and after this
operation, no change can be reverted back.
Here is a simple example to call commit method.
db.commit()
Disconnecting Database
To disconnect Database connection, use close() method.
db.close()
Database Operations (CRUD)
CRUD is an acronym that comes from the world of computer programming and refers to the four functions that
are considered necessary to implement a persistent storage application: create, read, update and delete.

Sample Create Operation


import mysql.connector
from mysql.connector import Error

name=input("Enter product name: ")


desc=input("Enter product description: ")
price=input("Enter product price: ")
quantity=input("Enter product quantity: ")

try:
con=mysql.connector.connect(host='localhost',
database='inventorysystem', username='root', password='')
query="INSERT INTO product(NAME,DESCRIPTION,PRICE,QUANTITY) VALUES
('"+ name +"', '"+ desc +"', '"+ price +"', '"+ quantity +"')"
cur=con.cursor()
cur.execute(query)
con.commit()
cur.close()
print("You have successfully inserted a product.")

except Error as error:


print("Insertion data failed.{}".format(error))

finally:
if con.is_connected():
con.close()
print("MYSQL connection is now closed.")

Sample Read Operation


import mysql.connector
from mysql.connector import Error

try:
con=mysql.connector.connect(host='localhost',
database='inventorysystem', username='root', password='')
query="SELECT * FROM product"
cur=con.cursor()
cur.execute(query)
records = cur.fetchall()
print("Number of records in the table:", cur.rowcount)
for row in records:
print("ID : ", row[0])
print("NAME : ", row[1])
print("DESCRIPTION : ", row[2])
print("PRICE : ", row[3])
print("QUANTITY : ", row[4])
print("-----------------------")

except Error as error:


print("Error in the program.{}".format(error))

finally:
if con.is_connected():
cur.close()
con.close()
print("MYSQL connection is now closed.")
Sample Update Operation
import mysql.connector
from mysql.connector import Error

try:
con=mysql.connector.connect(host='localhost',
database='inventorysystem', username='root', password='')
prod_id= input("Enter product ID: ")

#BEFORE THE UPDATE


select_query= "SELECT * FROM product WHERE ID='"+ prod_id +"'"
cur=con.cursor()
cur.execute(select_query)
record=cur.fetchone()
print(record)

#AFTER THE UPDATE


name= input("Update product name: ")
desc= input("Update product description: ")
price= input("Update product price: ")
quan= input("Update product quantity: ")
update_query = "UPDATE product SET NAME='"+ name +"', DESCRIPTION='"+
desc \
+"', PRICE='"+ price +"', QUANTITY='"+ quan +"' WHERE
ID='"+ prod_id +"'"
cur.execute(update_query)
con.commit()
print("You have successfully updated a record!")
print("--------------------------------------")
print("DATA AFTER THE UPDATE:")
cur.execute(select_query)
record = cur.fetchone()
print(record)

except Error as error:


print("Update failed:{}".format(error))
finally:
if con.is_connected():
cur.close()
con.close()
print("MySQL connection is now closed!")

Sample Delete Operation


import mysql.connector
from mysql.connector import Error

try:
con=mysql.connector.connect(host='localhost',
database='inventorysystem', username='root', password='')
query="SELECT * FROM product"
cur=con.cursor()
cur.execute(query)
records = cur.fetchall()
print("Number of records in the table:", cur.rowcount)
for row in records:
print("ID : ", row[0])
print("NAME : ", row[1])
print("DESCRIPTION : ", row[2])
print("PRICE : ", row[3])
print("QUANTITY : ", row[4])
print("-----------------------")

#To DELETE a Record


del_id = input("Enter ID Number: ")
del_query = "Delete FROM product WHERE ID = '"+ del_id +"'"
cur.execute(del_query)
con.commit()
print("You have successfully deleted a record!")

except Error as error:


print("Error in the program.{}".format(error))

finally:
if con.is_connected():
cur.close()
con.close()
print("MYSQL connection is now closed.")

You might also like