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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值