Python uses the pymysql module to connect to the MySQL database

Python3 connects to MySQL

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

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.

PyMySQL installation

pip3 install PyMySQL

Connect to the database

Precautions

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

basic use

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", password="password", database="database name", charset="utf8")
# Get a cursor object that can execute SQL statements
cursor = conn.cursor()
# Define the SQL statement to execute
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()

 

Return data in dictionary format:

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", password="password", database="database name", charset="utf8")
# Get a cursor that can execute an SQL statement and return the result as a dictionary
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# Define the SQL statement to execute
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()

Notice:

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

 

Add, delete, modify and check operations

increase

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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 the SQL statement
cursor.execute(sql, [username, age])
# commit transaction
conn.commit()
cursor.close()
conn.close()

Failed to insert data rollback

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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])
    # commit transaction
    conn.commit()
except Exception as e:
    # If there is an exception, roll back the transaction
    conn.rollback()
cursor.close()
conn.close()

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

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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])
    # commit 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()

batch execution

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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:
    # Batch execute multiple insert SQL statements
    cursor.executemany(sql, data)
    # commit transaction
    conn.commit()
except Exception as e:
    # If there is an exception, roll back the transaction
    conn.rollback()
cursor.close()
conn.close()

delete

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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 transaction
    conn.commit()
except Exception as e:
    # If there is an exception, roll back the transaction
    conn.rollback()
cursor.close()
conn.close()

change

# Import the pymysql module
import pymysql
# connect database
conn = pymysql.connect(host="your database address", user="username", 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 the SQL statement
    cursor.execute(sql, [age, username])
    # commit transaction
    conn.commit()
except Exception as e:
    # If there is an exception, roll back the transaction
    conn.rollback()
cursor.close()
conn.close()

 

check

Query a single piece of data

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

Query multiple pieces of data

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

Advanced usage

# Get the specified amount of data
cursor.fetchmany(3)
# The cursor moves by 1 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=324887840&siteId=291194637