python3 连接数据库

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 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()



展开阅读全文

页面更新:2024-03-24

标签:可防止   版本   操作   环境   教程   数据   列表   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top