import pymysql # 导入
conn = pymysql.connect(host="localhost", port=3306, db="db_py", user="root", password="root") # 创建连接 网络
# 获取游标
cursor = conn.cursor()
# 执行SQL语句
# 不要拼接SQL语句,否则可能会触发SQL注入漏洞
# cursor.execute("select * from t_user WHERE id = %s", (5,))
# MYSQL需要事物提交
try:
str_1 = "update t_user set name = %s ,gender = %s where id = %s"
count = cursor.execute(str_1, ['kk', 'women', 7])
conn.commit()
# 获取结果集
# users = cursor.fetchone()
# 打印
if count > 0:
print("Update Successful")
else:
print("No Successful")
except Exception as e:
conn.rollback()
print("ERRO")
finally:
# 关闭资源
cursor.close()
conn.close()
封装好的
import pymysql
class SqlHelper(object):
def __init__(self,host,port,db,user,password,charset="utf8"):
self.host = host
self.port = port
self.db = db
self.user = user
self.password = password
self.charset = charset
def connection(self):
self.conn = pymysql.connect(host=self.host,port=self.port,db=self.db,user=self.user,password=self.password,\
charset=self.charset)
self.cursor = self.conn.cursor()
# 返回值的第一个参数是影响的行数
# 第二个参数是查询的结果
def queryOne(self,sql,params):
try:
self.connection()
count = self.cursor.execute(sql,params)
res = self.cursor.fetchone()
return count,res
except Exception as e:
print("查询失败,失败信息是:",e)
finally:
self.close()
# 返回值的第一个参数是影响的行数
# 第二个参数是查询的结果
def queryAll(self, sql, params):
try:
self.connection()
count = self.cursor.execute(sql, params)
res = self.cursor.fetchall()
return count, res
except Exception as e:
print("查询失败,失败信息是:", e)
finally:
self.close()
return None
def update(self,sql,params):
try:
self.connection()
count = self.cursor.execute(sql,params)
self.conn.commit() #提交事务
return count
except Exception as e:
print("更新失败,失败信息是:%s" %e)
self.conn.rollback() # 回滚事务
finally:
self.close()
return None
def close(self):
if self.cursor != None:
self.cursor.close()
if self.conn != None:
self.conn.close()
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。