import pymysql
from pymysql.cursors import DictCursor
from pymysql import Error
"""
以面向对象的方式整理一下python链接数据库
"""
class Python_Mysql(object):
def __init__(self):
self.conn=self.connect_db()
def connect_db(self):
# 创建链接
try:
conn=pymysql.connect(
host="127.0.0.1",
user="root",
password="root",
database="my_news",
port=3306,
cursorclass=DictCursor
)
return conn
except Error as e:
print(e)
def close_conn(self):
# 关闭链接
try:
if self.conn is not None:
self.conn.close()
print("数据库关闭成功")
except Exception as e:
print("数据库关闭失败")
def get_one(self):
# sql="select * from user;"
sql="select * from user where name=%s;" # 防止sql的注入
with self.conn.cursor() as cursor:
cursor.execute(sql,("lili"))
result=cursor.fetchone() # 查询一条数据
# # result=cursor.fetchall() # 查询所有的数据
# result=cursor.fetchmany(3) # 查询多个的数据
return result
def assert_one(self):
sql='insert into user (name,pwd) VALUES ("lili","12345");'
with self.conn.cursor() as cursor:
cursor.execute(sql)
self.conn.commit()
print("插入数据完成")
def update_one(self):
sql='UPDATE user set name="l78ili" where id=7;'
with self.conn.cursor() as cursor:
cursor.execute(sql)
self.conn.commit()
print("插入数据完成")
def shiwu(self):
sql1='UPDATE user set name="l9ili" where id=7;'
sql2='UPDATE user set name="lli" where id=8;'
with self.conn.cursor() as cursor:
self.conn.begin()
cursor.execute(sql1)
cursor.execute(sql2)
self.conn.commit()
self.conn.close()
print("插入数据完成")
def main():
pymysql_1=Python_Mysql()
result=pymysql_1.shiwu()
# 关闭链接
pymysql_1.close_conn()
if __name__=="__main__":
main()
--来自盘超级会员V2的分享
hi,这是我用网盘分享的内容~复制这段内容打开「百度网盘」APP即可获取
链接:https://pan.baidu.com/s/1gIFlzdveT2ml-2CVNxs-4g
提取码:s99d