import pymysql

数据库连接

1
2
3
4
5
6
7
conn = pymysql.connect(  # 赋值给 conn连接对象
host=host, # 本地回环地址
port=port, # 默认端口
user=user, # 用户名
password=password, # 密码
database=databass, # 连接数据库名称
charset=charset # 编码 不能写utf-8

数据查询

1
2
3
4
5
6
7
8
9
10
11
# 生成一个游标对象(相当于cmd打开mysql中的 mysql>)
cursor = conn.cursor()
# 定义SQL语句
sql = 'select * from user'
# 执行SQL语句
ret = cursor.execute(sql)
print(ret) # 返回值是执行SQL语句之后受影响的行数
# 获取返回结果
# res = cursor.fetchall() # 获取所有记录列表
# res = cursor.fetchone() # 获取单条数据.
# res = cursor.fetchmany(3) # 列表套字典 几个数据

数据插入

1
2
3
4
5
6
cursor = conn.cursor()
sql = f'insert into work.menu (dish_name,dish_type,price,dish_id,time) values ("{dish_name}","{dish_type}","{dish_price}","{dish_id}",now())'
# 执行SQL语句
cursor.execute(sql)
conn.commit()
conn.close()