python3 连接数据库
版本:python3.8
安装连接包
windows环境
环境:windows10
https://blog.youkuaiyun.com/weixin_43570254/article/details/103101823~~
python -m pip install mysql-connector
参考教程:
https://www.runoob.com/python3/python3-mysql.html
连接及操作
from 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()