pymysql 数据库调用
# pymysql 数据库调用
- pymysql.connect (host,user,passwd,db,charset) 创建数据连接对象 返回 db 对象
- db.cursor () 创建游标 返回 cursor 对象
- db.commit () 提交事务
- cursor.execute (sql) 执行指定 sql 语句
- cursor.fetchall () 如果 cursor 有返回结果则使用此方法 读取返回结果
- close () 关闭
import pymysql
#创建连接
db = pymysql.connect(host='127.0.0.1',user='root',passwd='373213257',db='cov',charset='utf8') #charset是utf8而不是utf-8
#创建游标
cursor=db.cursor()
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") ## 使用 execute() 方法执行 SQL,如果表存在则删除
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql) #使用cursor.execute传入sql语句 sql存放是字符串
cursor.close() #关闭游标
db.close() #关闭数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
读取结果
sql ="""INSERT INTO history VALUES('2020-01-02',2,3,4,5,6,7)"""
cursor.execute(sql)
db.commit() #提交事务
cursor.execute("select * from history")
res = cursor.fetchall()
print(res)
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2023/12/06, 01:31:48