PYTHON MYSQL

mysql

reference : https://www.instructables.com

In this tutorial we learn about mysql .

Python MySQL

mysql database is an interface for connecting to a MySQL database server from Python.

in addition ,Python is use in database applications.

therefore ,One of the most popular databases is MySQL.

How to Install MySQL database

Before proceeding, you make sure you have MySQL database installed on your machine. therefore ,Just type the following in your Python script and execute it −

#!/usr/bin/python

import MySQLdb

finally ,If it produces the following as a result, then it means MySQLdb module is not installed −

Traceback (most recent call last):

File “test.py”, line 3, in <module>

   import MySQLdb

ImportError: No module named MySQLdb

in addition ,To install MySQLdb module, use the following command −

therefore ,For Ubuntu, use the following command –

 sudo apt-get install python-pip python-dev

libmysqlclient-dev For Fedora, use the following command –

$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc

For Python command prompt, use the following command –

pip install MySQL-python

Note − Make sure you have root privilege to install above module.

Database Connection

for example :

import MySQLdb

# Open database connection

db = MySQLdb. connect(“localhost”,“testuser”,“test123”,“TESTDB” )

cursr = db.cursor()

cursor.execute(“SELECT VERSION()”)

data = cursor .fetchone()

print “Database version : %s “ % data db.close()

therefore , If a connection is established with the datasource, in addition , then a Connection Object is returned and saved into db for further use, otherwise db is set to None. now therefore ,Next,therefore , db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, in addition , it ensures that database connection is closed and resources are released

Creating Database Table

Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.

for Example:

import MySQLdb

db = MySQLdb. (“localhost”,“testuser”,“test123”,“TESTDB” )

cursr = db.cursor()

cursor.execute(“DROP TABLE IF EXISTS EMPLOYEE”)

sql = “””CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )”””

cursr.execute(sql)

db.close()

INSERT Operation

It is required when you want to create your records into a database table.

for Example

The following example, executes SQL INSERT statement to create a record into EMPLOYEE table −

import MySQLdb

db = MySQLdb.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

cursor = db.cursor()

sql = “””INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (‘Mac’, ‘Mohan’, 20, ‘M’, 2000)””” try:  

     cursor.execute(sql)  

     db.commit()

except:

      db.rollback()

db.close()

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.

  • the 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.

for Example:

import MySQL

db db = MySQLdb.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

cursor = db.cursor()

sql = “SELECT * FROM EMPLOYEE \ WHERE INCOME > ‘%d'” % (1000)

try:  

   cursor.execute(sql)  

   results = cursor.fetchall()

   for row in results:

           fname = row[0

          lname = row[1]

         age = row[2]

         sex = row[3]

         income = row[4]      

         print “fname=%s,lname=%s,age=%d,sex=%s,income=%d” % \ (fname, lname, age, sex, income )

except:

     print “Error: unable to fecth data”

db.close()

Update Operation

UPDATE Operation on any database means to update one or more records, which are already available in the database.

The following procedure updates all the records having SEX as ‘M’. Here, we increase AGE of all the males by one year.

for Example

import MySQLdb

# Open database connection

db = MySQLdb.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

# prepare a cursor object using cursor()

method cursor = db.cursor()

# Prepare SQL query to UPDATE required records

sql = “UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ‘%c'” % (‘M’)

try:

# Execute the SQL command

cursor.execute(sql)

# Commit your changes in the database

db.commit()

except:

# Rollback in case there is any error

db.rollback()

# disconnect from server

db.close()

DELETE Operation

DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 −

for Example

import MySQLdb

db = MySQLdb.connect(“localhost”,“testuser”,“test123”,“TESTDB” )

cursor = db.cursor()

sql = “DELETE FROM EMPLOYEE WHERE AGE > ‘%d'” % (20)

try:  

   cursor.execute(sql)

   db.commit()

except:

    db.rollback()

db.close()

Performing Transactions in mysql

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.

The Python DB API 2.0 provides two methods to either commit or rollback a transaction.

for Example

You already know how to implement transactions. Here is again similar example −

sql = “DELETE FROM EMPLOYEE WHERE AGE > ‘%d'” % (20)

try:    

cursor.execute(sql)  

     db.commit()

except:   

      db.rollback()

COMMIT Operation in mysql

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.

for example :

ROLLBACK Operation  in mysql

If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.

Here is a simple example to call rollback() method.

for example :

Disconnecting Database

To disconnect Database connection, use close() method.

If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

finally we have covered all topics relate with mysql , here we have seen about mysql , how to connect it , in addition with how to create database ,here we have seen read operation , write one .

we have seen many operations such as insert , delete in addition with rollback , commit ,

https://javatpoint.com

%d bloggers like this: