python连接MySQL数据库与html

发布时间: 2023-11-21 10:45 阅读: 文章来源:1MUMB108PS
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

连接及操作from constant import constimport pymysqldevdbcfg = const.DB_DEV_BASEhost = 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来获取最后一次自增的IDprint("the last rowid is ",cursor.lastrowid)connection.commit()#提交数据cursor.close()# 关闭连接connection.close()

•••展开全文