MySql插入数据(3)

【实例】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pymysql
# 创建与数据的连接
con = pymysql.connect(host='localhost', password='root', user='root', database='testmysql', port=3306)
# 创建游标对象
cur = con.cursor()
# 写插入数据库的sql
sql = 'insert into student(sno, sname, sex, age, score) values(%s, %s, %s, %s, %s)' # s要小写,不然会报unsupported format character 'S' (0x53) at index 72
try:
# 执行sql插入一条数据
# cur.execute(sql, (1100, '张三', '男', 33, 33.3))
# 插入多条数据
args = [(102, '张2', '男', 33, 33.3), (103, '张4', '男', 33, 33.3), (104, '张5', '男', 33, 33.3)] # 插入多条数据要用executemany
cur.executemany(sql, args)
con.commit()
print('插入成功')
except Exception as e:
print(e)
print('插入失败')
finally:
con.close()
cur.close()

转载请注明来源,欢迎指出任何有错误或不够清晰的表达。可以邮件至gxnucgb@qq.com

文章标题:MySql插入数据(3)

文章字数:155

本文作者:陈桂彬

发布时间:2019-07-26, 10:20:26

最后更新:2019-07-27, 16:00:04

原始链接:https://github.com/gxnucgb/gxnucgb.github.io/2019/07/26/MySql插入数据/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏

github