Python操作mysql数据库
复制代码
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78import pymysql def createUserTable(): conn = pymysql.connect('localhost', user="root", passwd="123456", db="test_zheng") cursor = conn.cursor() cursor.execute('drop table if exists user') sql = """ CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0""" cursor.execute(sql) cursor.close() # 先关闭游标 conn.close() # 再关闭数据库连接 print('创建数据表成功') def insertUser(): conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng") cursor = conn.cursor() insert = cursor.execute("INSERT into user (`name` ,age) VALUES ('tom',18);") cursor.close() conn.commit() conn.close() print('添加语句受影响的行数:', insert) def insertUser2(): conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng") cursor = conn.cursor() sql = "INSERT into user (`name` ,age) VALUES (%s,%s)" insert = cursor.execute(sql,("Jeff.zheng",18)) cursor.close() conn.commit() conn.close() print('添加语句受影响的行数:', insert) def updateUser(): conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng") cursor = conn.cursor() sql = "UPDATE `user` set age =21 where name='Jeff.zheng'" insert = cursor.execute(sql) cursor.close() conn.commit() conn.close() print('添加语句受影响的行数:', insert) def selectUser(): conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng") cursor = conn.cursor() sql = "select * from user" result = cursor.execute(sql) while 1 : res=cursor.fetchone() if res is None: break else: print(res) cursor.close() conn.commit() conn.close() print('添加语句受影响的行数:',result) if __name__ == '__main__': # createUserTable() selectUser()
不行的话就是pip install pymysql
下载一下依赖
最后
以上就是笨笨飞鸟最近收集整理的关于Python操作mysql数据库的全部内容,更多相关Python操作mysql数据库内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复