1、安装 pymysql 库
pip install pymysql
2、操作Mysql数据库
import pymysql
# 打开数据库链接
db = pymysql.connect(host='数据库IP', port='3306', user='用户名', passwd='密码'
, database='数据库')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute()方法执行SQL语句
cursor.execute('SQL语句')
# 使用 fetchone() 方法获取一条数据
data_one = cursor.fetchone()
# 使用 fetchall()方法获取所有数据
data_all = cursor.fetchall()
# 除了查询,其他修改操作(增,删,改)
try:
# 执行SQL语句
cursor.execute('SQL语句')
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 最后操作
cursor.close() # 关闭游标
db.close() # 关闭数据库
3、可以封装成类,和对应的方法
import pymysql
class DBConnection:
def __init__(self, ip='', port=3306, user='root', passwd='123456', db=''):
self.ip = ip
self.port = port
self.user = user
self.passwd = passwd
self.db = db
# 连接数据库
def getCon(self):
try:
conn =pymysql.connect(
host=self.ip,
port=self.port,
user=self.user,
passwd=self.passwd,
database=self.db)
return conn
except pymysql.Error as e:
print(f'mysqldb error :{e}')
#查
def select(self, sql):
try:
con = self.getCon()
cur = con.cursor() # 创建游标
cur.execute(sql) # 执行语句
result = cur.fetchall() # 匹配所有
return result
except pymysql.Error as e:
print(f'mysqldb error :{e}')
finally:
cur.close()
con.close()
# 改
def update(self, sql):
try:
con = self.getCon()
cur = con.cursor()
cur.execute(sql)
con.commit() # 提交事务
except pymysql.Error as e:
con.rollback()
print(f'mysqldb error :{e}')
finally:
cur.close()
con.close()
# 增
def insert(self, sql):
try:
con = self.getCon()
cur = con.cursor()
cur.execute(sql)
con.commit()
except pymysql.Error as e:
con.rollback()
print(f'mysqldb error :{e}')
finally:
cur.close()
con.close()
# 删
def delete(self, sql):
try:
con = self.getCon()
cur = con.cursor()
cur.execute(sql)
con.commit()
except pymysql.Error as e:
con.rollback()
print(f'mysqldb error :{e}')
finally:
cur.close()
con.close()