Python3.5 MySQL Database connection
In this article, we introduce Python3 to use Pymysql to connect the database, and to implement simple additions and deletions.
Why use Pymysql?
Pymysql is a library used in the pyhton3.x version to connect to the MySQL database, and the MYSQLDB library is used in Python2.
Pymysql Installation
Before using Pymysql, you need to be sure to install the Pymysql library.
Can be installed by using PIP
Pip Install Pymysql
Database connection
Before you connect to a database, verify the following:
- You have created the database TESTDB.
- You have created a table in the TestDB database t_table
- T_table fields are first_name, last_name, age, SEX, and INCOME.
- Connection database TestDB Use the user name "TestUser", the password is "test123", you can set your own or directly use the root user name and its password, MySQL database user authorization please use the GRANT command.
Instance
The following example connects to the TestDB database in the MySQL database:
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#Create a Cursor object using the cursor () method cursorcursor =db.cursor ()#Execute SQL Query using the Execute () methodCursor.execute ("SELECT VERSION ()")#Use the Fetchone () method to get a single piece of data.data =Cursor.fetchone ()Print("Database version:%s"%data)#To close a database connectionDb.close ()
Create a database table
If a database connection exists, you can use the Execute () method to create a table for the database, creating the table as follows T_table
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#Create a Cursor object using the cursor () method cursorcursor =db.cursor ()#Execute SQL using the Execute () method, or delete if the table existsCursor.execute ("DROP TABLE IF EXISTS t_table")#To create a table using Preprocessing statementssql ="""CREATE TABLE t_table (first_name char) not NULL, last_name char (+), age INT, S EX CHAR (1), INCOME FLOAT)"""cursor.execute (SQL)#To close a database connectionDb.close ()
Database Insert Operations
The following example inserts a record into table t_table using the Execute SQL INSERT statement:
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#get an operation cursor using the cursor () methodcursor =db.cursor ()#SQL INSERT statementsql ="""INSERT into T_table (first_name, last_name, age, SEX, INCOME) VALUES (' Mac ', ' Mohan ', ', ' M ', ') """Try: #Execute SQL statementcursor.execute (SQL)#commit to database executionDb.commit ()except: #Rollback If an error occursDb.rollback ()#To close a database connectionDb.close ()
Database query Operations
Python queries MySQL uses the Fetchone () method to get a single record, using the Fetchall () method to get multiple records.
- Fetchone (): The method gets the next query result set, which is an object
- Fetchall (): The method receives all returned result sets
- Fetchnum (N)
- RowCount: This is a read-only property and returns the number of rows affected after executing the Execute () method
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#get an operation cursor using the cursor () methodcursor =db.cursor ()#SQL Query Statementssql ="SELECT * from t_table WHERE INCOME > '%d '"% (1000)Try: #Execute SQL statementcursor.execute (SQL)#get list of all recordsResults =Cursor.fetchall () forRowinchResults:fname=Row[0] lname= Row[1] Age= Row[2] Sex= Row[3] Income= Row[4] #Print Results Print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"%(fname, lname, age, sex, income))except: Print("error:unable to FECTH data")#To close a database connectionDb.close ()
The results of the above script execution are as follows:
Fname=mac, Lname=mohan, age=20, Sex=m, income=2000
Database update operations
The update action is used to update the data in the data table, and the following instance modifies all the SEX fields in the T_table table to ' M ', and the Age field increments by 1:
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#get an operation cursor using the cursor () methodcursor =db.cursor ()#SQL UPDATE statementsql ="UPDATE EMPLOYEE SET age = age + 1WHERE SEX ='%c' "% (' M ')Try: #Execute SQL statementcursor.execute (SQL)#commit to database executionDb.commit ()except: #Roll Back when an error occursDb.rollback ()#To close a database connectionDb.close ()
Delete operation
#!/usr/bin/python3ImportPymysql#Open a database connectiondb = Pymysql.connect ("localhost","testuser","test123","TESTDB" )#get an operation cursor using the cursor () methodcursor =db.cursor ()#SQL DELETE statementsql ="DELETE from t_table WHERE > '%d '"% (20)Try: #Execute SQL statementcursor.execute (SQL)#Submit ChangesDb.commit ()except: #Roll Back when an error occursDb.rollback ()#Close ConnectionDb.close ()
Execution transactions
Transaction mechanisms ensure data consistency.
A transaction should have 4 properties: atomicity, consistency, isolation, persistence. These four properties are often called acid properties.
- Atomicity (atomicity). A transaction is an inseparable unit of work, and the operations included in the transaction are either done or not.
- Consistency (consistency). The transaction must be to change the database from one consistency state to another. Consistency is closely related to atomicity.
- Isolation (Isolation). Execution of one transaction cannot be disturbed by other transactions. That is, the operations inside a transaction and the data used are isolated from other transactions that are concurrently executing, and cannot interfere with each other concurrently.
- Persistence (durability). Persistence, also known as permanence (permanence), refers to the fact that once a transaction is committed, its changes to the data in the database should be permanent. The next operation or failure should not have any effect on it.
The transaction for Python DB API 2.0 provides two methods of commit or rollback.
# SQL Delete Record statement " DELETE from the EMPLOYEE WHERE age > '%d ' "%" try: # Execute SQL statement cursor.execute (SQL) # Submit to Database db.commit ()except: # rollback When an error occurs db.rollback ()
For a database that supports transactions, in Python database programming, when the cursor is established, an invisible database transaction is automatically started.
Commit () method all the update operations of the cursor, the rollback () method rolls back all operations of the current cursor. Each method starts a new transaction.
Transferred from: http://www.runoob.com/python3/python3-mysql.html
Python3.5 MySQL Database connection