python 中使用 mysql

注意:py中使用 mysql 需要提前安装 mysql 可以参考:mysql 逐步安装

安装pymysql

1
pip install pymysql

使用

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
29
30
31
32
33
34
35
import pymysql
import time


# 创建连接
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='123456',
database='test', # 数据库名称
charset='utf8'
)

# 创建游标
cursor = conn.cursor()

# 执行sql
# 注意:
# sql语句中的参数需要使用 %s 占位符
# 然后通过参数传递的方式传入参数,防止sql注入
sql = 'select * from user where create_time > %s'
times = time.mktime(time.strptime("2024-01-01 00:00:00","%Y-%m-%d %H:%M:%S"))
cursor.execute(sql, (times, ))

# 获取结果
result = cursor.fetchall()
print(result)

# 关闭游标
cursor.close()

# 关闭连接
conn.close()