Python learning Day16 Python3 MySQL database

Python3 MySQL database

Python3 uses  PyMySQL  to connect to the database and implement simple addition, deletion, modification and query.

What is PyMySQL?

PyMySQL is a library for connecting to MySQL servers in Python 3.x, and mysqldb in Python 2.

PyMySQL follows the Python Database API v2.0 specification and includes the pure-Python MySQL client library.

PyMySQL installation

Before using PyMySQL, we need to make sure that PyMySQL is installed.

PyMySQL download address: https://github.com/PyMySQL/PyMySQL.

If it is not already installed, we can install the latest version of PyMySQL with the following command:

$ pip install PyMySQL

If your system does not support the pip command, you can install it using:

1. Use the git command to download the installation package and install (you can also download it manually):

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install

2. If you need to specify the version number, you can use the curl command to install:

$ # XX is the version number of PyMySQL 
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-XX | tar xz
$ cd PyMySQL*
$ python3 setup.py install
$ # Now you can delete the PyMySQL* directory

Note: Make sure you have root privileges to install the above modules.

During the installation process, the error message "ImportError: No module named setuptools" may appear, which means that you do not have setuptools installed. You can visit https://pypi.python.org/pypi/setuptools  to find the installation method for each system.

Linux system installation example:

$ wget https://bootstrap.pypa.io/ez_setup.py
$ python3 ez_setup.py

Database linkage

Before connecting to the database, please confirm the following:

  • You have created the database TESTDB.
  • In the TESTDB database you have created the table EMPLOYEE
  • The EMPLOYEE table fields are FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
  • The user name used to connect to the database TESTDB is "testuser" and the password is "test123". You can set it yourself or use the root user name and password directly. For Mysql database user authorization, use the Grant command.
  • The Python MySQLdb module has been installed on your machine.

Example:

The following example links the Mysql TESTDB database:

Example (Python 3.0+)

#!/usr/bin/python3
 
import pymysql
 
#Open database connection 
db = pymysql.connect ( " localhost " , " testuser " , " test123 " , " TESTDB " )
 
#Use the cursor() method to create a cursor object cursor 
cursor = db.cursor()
 
#Use the execute() method to execute the SQL query 
cursor.execute( " SELECT VERSION() " )
 
#Use the fetchone() method to get a single piece of data. 
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
#Close the database connection 
db.close()

The output of executing the above script is as follows:

Database version : 5.5.20-log

Create database table

If the database connection exists we can use the execute() method to create a table for the database, as follows to create the table EMPLOYEE:

Example (Python 3.0+)

#!/usr/bin/python3
 
import pymysql
 
#Open database connection 
db = pymysql.connect ( " localhost " , " testuser " , " test123 " , " TESTDB " )
 
#Use the cursor() method to create a cursor object cursor 
cursor = db.cursor()
 
#Use the execute() method to execute SQL, if the table exists, delete 
cursor.execute( " DROP TABLE IF EXISTS EMPLOYEE " )
 
#Create table using prepared statements 
sql = """ CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
 
cursor.execute(sql)
 
#Close the database connection 
db.close()

database insert operation

The following example inserts records into table EMPLOYEE using the execute SQL INSERT statement:

Example (Python 3.0+)

#!/usr/bin/python3
 
import pymysql
 
#Open database connection 
db = pymysql.connect ( " localhost " , " testuser " , " test123 " , " TESTDB " )
 
#Use the cursor() method to get the operation cursor 
cursor = db.cursor()
 
# SQL insert statement 
sql = """ INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000) """ 
try :
    #Execute the sql statement 
   cursor.execute(sql)
    #Submit to the database and execute 
   db.commit()
 except :
    #If an error occurs, then rollback 
   db.rollback()
 
#Close the database connection 
db.close()

The above example can also be written as:

Example (Python 3.0+)

#!/usr/bin/python3
 
import pymysql
 
#Open database connection 
db = pymysql.connect ( " localhost " , " testuser " , " test123 " , " TESTDB " )
 
#Use the cursor() method to get the operation cursor 
cursor = db.cursor()
 
# SQL insert statement 
sql = " INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
       ( ' Mac ' , ' Mohan ' , 20, ' M ' , 2000 )
 try :
    #Execute the sql statement 
   cursor.execute(sql)
    #Execute the sql statement 
   db.commit()
 except :
    #rollback when an error occurs 
   db.rollback( )
 
#Close the database connection 
db.close()

The following code uses variables to pass parameters into the SQL statement:

..................................
user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \
             (user_id, password))
..................................

Database query operation

The Python query Mysql uses the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data.

  • fetchone():  This method fetches the next query result set. The result set is an object
  • fetchall():  Receives all returned result rows.
  • rowcount:  This is a read-only property and returns the number of rows affected by executing the execute() method.

Example:

Query all data in the salary field greater than 1000 in the EMPLOYEE table:

Example (Python 3.0+)

#!/usr/bin/python3
 
import pymysql
 
#Open database connection 
db = pymysql.connect ( " localhost " , " testuser " , " test123 " , " TESTDB " )
 
#Use the cursor() method to get the operation cursor 
cursor = db.cursor()
 
# SQL query statement 
sql = " SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d' " % (1000 )
 try :
    #Execute the SQL statement 
   cursor.execute(sql)
    #Get a list of all records 
   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 fetch data")
 
#Close the database connection 
db.close()

The result of executing the above script is as follows:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000

database update operation

The update operation is used to update the data of the data table. The following example modifies all the SEX fields in the TESTDB table to 'M' and increments the AGE field by 1:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325136470&siteId=291194637