python连接mysql

demo


1. 安装PyMySQL

$ pip install pymysql

github地址

2. select操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pymysql
connection = pymysql.connect(
host="localhost",
port = 3306,
user = "root",
password = "root",
db = "test",
charset = "utf8"
)
cur = connection.cursor()
cur.execute("select * from test")
# row = cur.fetchone()
# print (row)
res = cur.fetchall()
for row in res:
print (row)
connection.close()
val = input("press any key to exit ...")

3. insert操作

1
2
3
4
5
6
with connection.cursor() as cur:
sql = "insert into test(id, name, age, description) values(11,'tony',%s,%s)"
cur.execute(sql, (30, "this is description to tony ..."))
# connection is not autocommit by default.
# So you must commit to save your changes.
connection.commit()

4. 错误处理

1
2
3
4
5
6
7
# open the connection
# connection = pymysql.connect()
try:
# with connection.cursor() as cursor:
# do something with cursor
finally:
# close the conection

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 1. 安装PyMySQL
  2. 2. 2. select操作
  3. 3. 3. insert操作
  4. 4. 4. 错误处理
,