python3 连接数据库
版本:python3.8
安装连接包
windows环境
环境:windows10
https://blog.csdn.net/weixin_43570254/article/details/103101823~~
python -m pip install mysql-connector
参考教程:
https://www.runoob.com/python3/python3-mysql.html
连接及操作
复制代码
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
36from constant import const import pymysql devdbcfg = const.DB_DEV_BASE host = devdbcfg.get('host') port = devdbcfg.get('port') user = devdbcfg.get('user') password = devdbcfg.get('passwd') config ={ "host": host, "port": port, "user": user, "password": password } connection = pymysql.connect(**config) cursor = connection.cursor() # 获取列表 query_sql = "select * from tmp_table5 limit 10" cursor.execute(query_sql) data =cursor.fetchall() print(data) insert_sql = "INSERT INTO tmp_table3 (tmp1) VALUES ('帅死了')" cursor.execute(insert_sql) # 增、删、改的时候,必须要进行提交,否则插入的数据不生效。 connection.commit() # 在execute提供插入的数据 -> 可防止sql注入 insert_sql_template = "INSERT INTO tmp_table3 (tmp1) VALUES (%s)" cursor.execute(insert_sql_template,("你太帅了,没错")) # 自增的主键,可以使用lastrowid来获取最后一次自增的ID print("the last rowid is ",cursor.lastrowid) connection.commit() #提交数据 cursor.close() # 关闭连接 connection.close()
最后
以上就是朴素微笑最近收集整理的关于python3 连接数据库python3 连接数据库的全部内容,更多相关python3内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复