The use of python connection database pymysql module

A Python3 connection to MySQL

  This article introduces the basic use of PyMySQL, a third-party library for Python3 to connect to MySQL.

 

1 Introduction to PyMySQL

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

  You can also use PyMySQL to connect to MySQL databases in Django.

2 PyMySQL installation

pip install pymysql

Two connection database

Note before proceeding with the following content in this article:

  • You have a MySQL database, and it has been started.
  • You have a username and password that can connect to the database
  • You have a database that you have permission to operate on

Notice:

charset="utf8", do not write the encoding as "utf-8"

1 Basic use

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor() #Define
 the SQL statement to be executed 
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
""" 
#Execute the SQL statement 
cursor.execute(sql)
 #Close the cursor object 
cursor.close() #Close
 the database connection 
conn.close()

2 Return data in dictionary format:

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor that can execute the SQL statement and return the result as a dictionary cursor = conn.cursor 
(cursor= pymysql.cursors.DictCursor) #Define
 the SQL statement to be executed 
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
""" 
#Execute the SQL statement 
cursor.execute(sql)
 #Close the cursor object 
cursor.close() #Close
 the database connection 
conn.close()

Three additions, deletions, changes, and search operations

1 increase

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor()
sql = " INSERT INTO USER1(name, age) VALUES (%s, %s); " 
username = " Alex " 
age = 18
 #Execute SQL statement 
cursor.execute(sql, [username, age])
 #Submit transaction 
conn. commit()
cursor.close()
conn.close()

2 Failed to insert data and rollback

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor()
sql = " INSERT INTO USER1(name, age) VALUES (%s, %s); " 
username = " Alex " 
age = 18
 try :
     #Execute the SQL statement 
    cursor.execute(sql, [username, age]) #Submit
     the transaction 
    conn.commit()
 except Exception as e:
     #There is an exception, rollback the transaction conn.rollback     ()

cursor.close()
conn.close()

3 Get the ID of the inserted data (used in the association operation)

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor()
sql = " INSERT INTO USER1(name, age) VALUES (%s, %s); " 
username = " Alex " 
age = 18
 try :
     #Execute the SQL statement 
    cursor.execute(sql, [username, age]) #Submit
     the transaction 
    conn.commit() #After
     submitting , get the ID of the data just inserted 
    last_id = cursor.lastrowid
 except Exception as e:
     #If there is an exception, roll back the transaction 
    conn.rollback()
cursor.close()
conn.close()

4 batch execution

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor()
sql = " INSERT INTO USER1(name, age) VALUES (%s, %s); " 
data = [( " Alex " , 18), ( " Egon " , 20), ( " Yuan " , 21 )]
 try :
     #Execute multiple insert SQL statements in batches 
    cursor.executemany(sql, data)
     #Submit the transaction 
    conn.commit()
 except Exception as e:
     #If there is an exception, roll back the transaction 
    conn.rollback()
cursor.close()
conn.close()

5 delete

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [ 4 ])
     #Commit the transaction 
    conn.commit()
 except Exception as e:
     #If there is an exception, roll back the transaction 
    conn.rollback()
cursor.close()
conn.close()

6 change

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor() #SQL
 statement to modify data 
sql = " UPDATE USER1 SET age=%s WHERE name=%s; " 
username = " Alex " 
age = 80
 try :
     #Execute SQL statement     cursor.execute(sql, [age, username])
     #Commit transaction     conn.commit()
 except Exception as e:
     #

There is an exception, rollback the transaction 
    conn.rollback()
cursor.close()
conn.close()

7 check

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor() #Query
 data SQL statement 
sql = " SELECT id,name,age from USER1 WHERE id=1; " #Execute SQL statement cursor.execute(sql)
 #Get a single query data 
ret = cursor.fetchone()


cursor.close()
conn.close()
#Print the query result 
print (ret)

8 Query multiple pieces of data

#Import pymysql module 
import pymysql #Connect
 database conn 
= pymysql.connect(host="your database address", user="user name", password="password", database="database name", charset= "utf8")
 #Get a cursor object that can execute SQL statements 
cursor = conn.cursor() #Query
 data SQL statement 
sql = " SELECT id,name,age from USER1; " #Execute SQL statement cursor.execute(sql)
 #Get multiple Query data 
ret = cursor.fetchall()


cursor.close()
conn.close()
#Print the query result 
print (ret)

Four advanced usage

#You can get the specified amount of data 
cursor.fetchmany(3 )
 #The cursor moves 1 according to the absolute position 
cursor.scroll(1, mode= " absolute " )
 #The cursor moves 1 according to the relative position (current position) 
cursor.scroll(1, mode = " relative " )

 

Guess you like

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