[Python] From entry to top—mysql database operation module mysql-connector and PyMySQL application scenarios (15)

mysql-connector

MySQL officially provides the mysql-connector-python driver

  1. install driver

    python -m pip install mysql-connector
    
  2. Connect to the database to get the connection

    import mysql.connector
    
    db = mysql.connector.connect(
        host="localhost", #ip
        user="root", #用户名
        passwd="root",#密码
        database="python_test",#连接数据库
        auth_plugin='mysql_native_password'
    )
    #获取游标
    cursor = db.cursor()
    

Create database

cursor.execute("CREATE DATABASE python_test")

Output a list of all databases:

cursor.execute("SHOW DATABASES")
for x in cursor:
    print(x)
"""
('basic_project',)
('ceam_mall2',)
('information_schema',)
('jwt-demo',)
('liugh',)
('mysql',)
('niu_b_xx_hou',)
"""

Create data table

cursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")

Output all database tables:

cursor.execute("SHOW TABLES")
for x in cursor:
    print(x)
#('sites',)

Primary key settings

cursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

Insert data

#sql
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
#占位符插入数据
val = ("RUNOOB", "https://www.baidu.com")
#执行sql
cursor.execute(sql, val)

db.commit()
print(cursor.rowcount, "记录插入成功。")

Batch insert

  • Batch insert executemany() method, the second parameter of this method is a list of tuples, containing the data we want to insert:
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
    ('Google', 'https://www.google.com'),
    ('Github', 'https://www.github.com'),
    ('Taobao', 'https://www.taobao.com'),
    ('stackoverflow', 'https://www.stackoverflow.com/')
]
#执行sql
cursor.executemany(sql, val)
#提交事务: 数据表内容有更新,必须使用到该语句
db.commit()
print(cursor.rowcount, "记录插入成功。")

If we want to get the ID of the data record after it is inserted, we can use the following code:

sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("Zhihu", "https://www.zhihu.com")
cursor.execute(sql, val)
db.commit()
print("1 条记录已插入, ID:", cursor.lastrowid)

Query data

cursor.execute("SELECT * FROM sites")
result = cursor.fetchall()  # fetchall() 获取所有记录
for x in result:
	print(x)
"""
('RUNOOB', 'https://www.runoob.com', 1)
('Google', 'https://www.google.com', 2)
('Github', 'https://www.github.com', 3)
('Taobao', 'https://www.taobao.com', 4)
('stackoverflow', 'https://www.stackoverflow.com/', 5)
('Zhihu', 'https://www.zhihu.com', 6)
"""

If we only want to read one piece of data, we can use the fetchone() method:

cursor.execute("SELECT * FROM sites")
result = cursor.fetchone()
print(result)

In order to prevent SQL injection attacks in database queries, we can use %s 占位符来转义查询的条件:

sql = "SELECT * FROM sites WHERE name = %s"
na = ("RUNOOB",)
cursor.execute(sql, na)
result = cursor.fetchall()
for x in result:
    print(x)

delete

sql = "DELETE FROM sites WHERE name = %s"
na = ("stackoverflow",)
cursor.execute(sql, na)
db.commit()
print(cursor.rowcount, " 条记录删除")

renew

sql = "UPDATE sites SET name = %s WHERE name = %s"
val = ("Zhihu", "ZH")
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, " 条记录被修改")

close connection

#最后一定要关闭数据库连接
db.close()

Python连接MySQL报错:mysql.connector.errors.NotSupportedError: Authentication plugin ‘caching_sha2_password’ is not supported

  • Add a statement (auth_plugin='mysql_native_password') and add the following code:

Insert image description here

summary

  • commit()A commit transaction must be called after performing operations such as INSERT/UPDATE/DELETE ;
  • SQL placeholders for MySQL are %s.

PyMySQL

PyMySQL is in Python3.x 版本中用于连接 MySQL 服务器的一个库, and Python2 uses mysqldb.

  • PyMySQL follows Python 数据库 API v2.0 规范and includes 了 pure-Python MySQL client libraries.
  1. Install

    pip3 install PyMySQL
    
  2. Database Connectivity

    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         database='python_test')
     
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
     
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT VERSION()")
     
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
     
    print ("Database version : %s " % data)
     
    # 关闭数据库连接
    db.close()
    

Create database table

import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
 
# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
 
cursor.execute(sql)
 
# 关闭数据库连接
db.close()

Database insert operation

import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

The above example can also be written in the following form:

import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s',  %s,  '%s',  %s)" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
try:
   # 执行sql语句
   cursor.execute(sql)
   # 执行sql语句
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

Database query operations

  • Python queries Mysql using the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data.

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

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

import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > %s" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   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=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

Database update operations

  • Increment the AGE field in the TESTDB table with SEX of 'M' by 1:
import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

Delete operation

  • Delete all data in the data table EMPLOYEE with AGE greater than 20:
import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交修改
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭连接
db.close()

Execute transaction

  • Python DB API 2.0 transactions provide two methods commit 或 rollback.
# SQL删除记录语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 向数据库提交
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
  • For databases that support transactions, in Python database programming, when the cursor is created, an invisible database transaction is automatically started.

    • The commit() method commits all update operations of the current cursor, and the rollback() method rolls back all operations of the current cursor. Each method starts a new transaction.

Guess you like

Origin blog.csdn.net/qq877728715/article/details/132853653