引进包
import pymysql
db = pymysql.connect(
host="192.168.2.123",
port=9059,
user="root",
password="sk197311",
database="test"
)
curses = db.cursor()
# 执行sql命令查看版本号
curses.execute('select version()')
data = curses.fetchone()
查看a表
curses.execute('select * from a')
re = curses.fetchall()
print(re)
for row in re:
id = row[0]
name = row[1]
print("id = %s, names = %s" % (id, name))
print(data)
增加数据进a数据库
try:
curses.execute("insert into a values(null, '赵六1')")
db.commit()
except:
db.rollback()
批量增加,如果需要字不一样,需要自定义
这个格式化字符串需要双重符号,具体解答不知道吗,应该是多层对象


这篇博客展示了如何使用Python的pymysql模块连接到MySQL数据库,执行查询和插入操作。通过示例代码,解释了如何获取数据库版本信息、查询特定表的数据,并进行数据的插入。此外,还涉及到了事务处理,确保数据操作的原子性。
5万+

被折叠的 条评论
为什么被折叠?



