The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as −
- GadFly
- mSQL
- MySQL
- PostgreSQL
- Microsoft SQL Server 2000
- Informix
- Interbase
- Oracle
- Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.
Install MySQL Driver
Python needs a MySQL driver to access the MySQL database.
In this tutorial we will use the driver "MySQL Connector".
We recommend that you use PIP to install "MySQL Connector".
PIP is most likely already installed in your Python environment.python -m pip install mysql-connector-python
Test MySQL Connector
To test if the installation was successful, or if you already have "MySQL Connector" installed, create a Python page with the following content:
import mysql.connector
- If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used.
Create Connection
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="" ) print(mydb)
on executing following code it produces:
<mysql.connector.connection.MySQLConnection object at 0x000001E56DF80D48>
If a connection is established with the datasource, then a Connection Object is returned.
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mypythondb")
Show DATABASES
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="" ) mycursor = mydb.cursor() mycursor.execute("show databases") for x in mycursor: print(x)
('information_schema',) ('test',)
connecting DATABASE
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() mycursor.execute("show tables") for x in mycursor: print(x)
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.
Example
Let us create Database table EMPLOYEE −
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE users (name VARCHAR(255), email VARCHAR(255), age INTEGER(10), user_id INTEGER AUTO_INCREMENT PRIMARY KEY)") mycursor.execute("SHOW TABLES") for x in mycursor: print(x)
- output
('users',)
INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record into users table −
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() sqlStuff = "INSERT INTO users (name, email, age) VALUES (%s, %s, %s)" record1 = ("John", "john@codemy.com", 40)#INSERT ONE RECORD mycursor.execute(sqlStuff, record1) mydb.commit()
insert many records
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() #INSERT MULTIPLE RECORDS sqlStuff = "INSERT INTO users (name, email, age) VALUES (%s, %s, %s)" records = [("Tim", "tim@tim.com", 32), ("Mary", "Mary@mary.com", 21), ("Steve", "steve@steveEmail.com", 57), ("Tina", "tina@somethingellse.com", 29),] mycursor.executemany(sqlStuff, records) mydb.commit()
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.
Example
The following procedure queries all the records from useres table having
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() #PULL DATA FROM THE TABLE mycursor.execute("SELECT * FROM users") result = mycursor.fetchall() print("NAMEtEMAILtttAGEtID") print("----t-----ttt---t---") for row in result: print(row[0] + "t%s" %row[1] + "tt%s" %row[2] + "t%s" %row[3])
- Output:
NAME EMAIL AGE ID ---- ----- --- --- John john@codemy.com 40 1 Tim tim@tim.com 32 2 Mary Mary@mary.com 21 3
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 name as 'Tim'. Here, we increase AGE to 35.Example
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() my_sql = "UPDATE users SET age = 35 WHERE user_id = 2" mycursor.execute(my_sql) mydb.commit()
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 users where AGE is more than 35 −
Example
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mypythondb" ) mycursor = mydb.cursor() #PULL DATA FROM THE TABLE mycursor.execute("SELECT * FROM users") result = mycursor.fetchall() print("NAMEtEMAILtttAGEtID") print("----t-----ttt---t---") for row in result: print(row[0] + "t%s" %row[1] + "tt%s" %row[2] + "t%s" %row[3])
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.mydb.commit()
ROLLBACK Operation
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.mydb.rollback()
Disconnecting Database
To disconnect Database connection, use close() method.
mydb.close()
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.
Handling Errors
There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.
The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.Sr.No. Exception & Description 1 Warning Used for non-fatal issues. Must subclass StandardError.
2 Error Base class for errors. Must subclass StandardError.
3 InterfaceError Used for errors in the database module, not the database itself. Must subclass Error.
4 DatabaseError Used for errors in the database. Must subclass Error.
5 DataError Subclass of DatabaseError that refers to errors in the data.
6 OperationalError Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
7 IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.
8 InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.
9 ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.
10 NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality.
Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.