Detailed explanation of PyMySQL operation in Python

1. Introduction to PyMysql

PyMySQL is a library used to connect to the MySQL server in Python 3.x, and mysqldb is used in Python 2.x.

You can also use PyMySQL to connect to the MySQL database in Django.

2. Detailed explanation of PyMySQL operation

2.1 PyMySQL installation

pip install pymysql

2.2 PyMySQL application

2.2.1 Basic use

# coding=utf8

import sys
import pymysql
import time

# 连接database
conn = pymysql.connect(host="数据服务器IP", user="用户名",password="密码",database="数据库名",charset="utf8")
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
sql = """
CREATE TABLE user (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()

2.2.2 Prevent SQL injection

# coding=utf8

import sys
import pymysql
import time

name = input("姓名:>>")
age = input("年龄:>>")
# 连接数据库
conn = pymysql.connect(host="数据服务器IP", user="用户名",password="密码",database="数据库名",charset="utf8")
# 获取光标,输入SQL语句并执行
cursor = conn.cursor()

# 自己拼接字符串,容易造成SQL注入问题
sql1 = "select * from user where name='%s' and age='%s';"%(name,age)
ret1 = cursor.execute(sql1)

# 让pymysql来拼接,防止SQL注入
sql2 = "select * from user where name=%s and age=%s;"
ret2 = cursor.execute(sql2,[name,age])

# 关闭光标和连接
cursor.close()
conn.close()
print(ret2)

2.2.3 Processing database operations with transactions

# coding=utf8

import sys
import pymysql
import time

# 连接数据库
conn = pymysql.connect(host="数据服务器IP", user="用户名",password="密码",database="数据库名",charset="utf8")
# 获取光标,输入SQL语句并执行
cursor = conn.cursor()

# 写SQL语句(ignore 忽略已存在的数据,保证批量添加全部执行)
sql = "INSERT IGNORE INTO user(name,age) VALUES(%s,%s);"
name1 = "王芳"
age1 = 29
name2 = "刘广"
age2 = 31
try:
    # 单条添加
    #cursor.execute(sql, [name1, age1])
    # 多条添加
    cursor.executemany(sql, ((name1, age1),(name2, age2)))

    # 把修改提交到数据库
    conn.commit()
except Exception as e:
    conn.rollback()  # 执行SQL语句有问题或提交有异常都回滚

cursor.close()
conn.close()

2.2.4 Dynamically obtain data

# coding=utf8

import sys
import pymysql
import time

# 连接数据库
conn = pymysql.connect(host="数据服务器IP", user="用户名",password="密码",database="数据库名",charset="utf8")
# 获取光标,输入SQL语句并执行
cursor = conn.cursor()

# 查询数据
sql = """ 
SELECT * FROM user LIMIT 2,10; 
"""
cursor.execute(sql)

# 获取所有查询到的结果
ret1 = cursor.fetchall()
print(ret1)

# 从查询语句中获取一条查询结果
# ret2 = cursor.fetchone()
# print(ret2)

# 获取相应的行数
# ret3 = cursor.fetchmany(2)
# print(ret3)

# 返回执行的sql语句
# ret4 = cursor.mogrify(sql)
# print(ret4)

conn.commit()

cursor.close()
conn.close()

Guess you like

Origin blog.csdn.net/m0_68949064/article/details/133983616