Last updated on July 1, 2025 am
安装 PyMySQL
操作数据库
开启 mysql 地址为 localhost:3306 用户名为 root 密码为 root
1 2 3 4 5 6 7
| import pymysql dbconn = pymysql.connect( host='localhost', user='root', password='root', database='test' )
|
- 使用 cursor() 方法创建一个游标对象 cursor
1
| cursor = dbconn.cursor()
|
1
| cursor.excute("select user()")
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import pymysql
db = pymysql.connect(host='localhost', user='testuser', password='test123', database='TESTDB')
cursor = db.cursor()
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()
|
使用预处理方法防止SQL注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import pymysql
db = pymysql.connect(host='localhost', user='testuser', password='test123', database='TESTDB')
cursor = db.cursor() sql = 'SELECT * FROM user where username = %s' cursor.execute(sql,(username,))
db.close()
|
Python-PyMySQL
https://blog.lixey.top/posts/db284c9b/