pymysql查看、更新数据库
1.查看
# 打开数据库连接 db = pymysql.connect("127.0.0.1", "root", "9jA6FT!dQvbo", "ops") # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 查询语句 sql = "SELECT * FROM news WHERE live_id = %s" % self.live_id try: # 执行SQL语句 k1 = {} cursor.execute(sql) # print(cursor.rownumber) col = cursor.description result = cursor.fetchone() for i in range(len(col)): # l1.append(col[i][0]) k1[col[i][0]]=result[i] # print(k1) return k1 except: error ="Error: unable to fetch data" return error # 关闭数据库连接 db.close()
2.更新数据库
# 打开数据库连接 db = pymysql.connect("localhost", "root", "9jA6FT!dQvbo", "ops") # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 查询语句 sql = "update news set live_video=\"%s\" WHERE live_id = %d" % (self.live_video, int(self.live_id)) try: # 执行SQL语句 cursor.execute(sql) db.commit() db.rollback() result = self.list_db() return result except: error = "Error: unable to fetch data" return error # 关闭数据库连接 db.close()