安装pymysql:
一、安装
1
|
pip3 install pymysql
|
二、使用操作
1、执行SQL
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
|
#!/usr/bin/env pytho
# -*- coding:utf-8 -*-
import
pymysql
# 创建连接
conn
=
pymysql.connect(host
=
'127.0.0.1'
, port
=
3306
, user
=
'root'
, passwd
=
'
', db='
tkq1
', charset='
utf8')
# 创建游标
cursor
=
conn.cursor()
# 执行SQL,并返回收影响行数
effect_row
=
cursor.execute(
"select * from tb7"
)
# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))
# 执行SQL,并返回受影响行数,执行多次
#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)",
[("u1","u1pass","11111"),("u2","u2pass","22222")])
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
|
实例: 查询数据库中student表数据:
#请求mysql数据库的数据 import pymysql #创建连接 conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='000000', db='myschool', charset='utf8') # 创建游标 cursor = conn.cursor() #查询数据库 cursor.execute('SELECT studentName,phone FROM student'); for i in cursor.fetchall(): print(i) conn.commit() cursor.close() conn.close()
运行结果: