import pymysql
# 打开数据库连接
db = pymysql.connect(localhost, user, pwd, "orders")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
eventId = '123456'
sql = "select * from so where doorEventId='%s'" % eventId
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
if len(results) > 0:
for row in results:
print(row[0])
else:
print("no result")
# 提交事务(查询操作不需要提交)
# db.commit()
except Exception as e:
print("Error: unable to fetch data", e)
# 回滚(查询操作不需要回滚)
# db.rollback()
#关闭游标
cursor.close()
# 关闭数据库连接
db.close()
# 增
sql_insert = "INSERT INTO operation(deviceCode,deviceName) VALUES(%s,%s)"
cursor.execute(sql_insert, ('1234', 'testDevice'))
或者
sql_insert = "INSERT INTO operation(deviceCode,deviceName) VALUES ('1234', 'testDevice')"
cursor.execute(sql_insert)
# 删
sql_delete = 'DELETE FROM info WHERE age > 28'
# 改
sql_update = "UPDATE device_operation SET status = %s WHERE ID = %s" % (status, operationId)
Python pymysql的使用
最新推荐文章于 2025-04-25 22:06:57 发布