import pymysql
class DataBaseHandle(object):
‘‘‘ 定义一个 MySQL 操作类‘‘‘
def __init__(self, host, username, password, database, port):
‘‘‘初始化数据库信息并创建数据库连接‘‘‘
# 下面的赋值其实可以省略,connect 时 直接使用形参即可
self.host = host
self.username = username
self.password = password
self.database = database
self.port = port
self.db = pymysql.connect(
host=self.host,
user=self.username,
password=self.password,
db=self.database,
port=self.port,
charset="utf8"
)
self.cursor = self.db.cursor(pymysql.cursors.DictCursor)
self.cursor.execute(sql)
# tt = self.cursor.execute(sql) # 返回 插入数据 条数 可以根据 返回值 判定处理结果
# print(tt)
self.db.commit()
# query = ‘insert into 表名(列名1, 列名2, 列名3, 列名4, 列名5, 列名6) values(%s, %s, %s, %s, %s, %s)‘
# self.cursor.execute(sql)
except Exception as e:
# 发生错误时回滚
self.db.rollback()
raise e
finally:
self.cursor.close()
def select_info(self, sql):
‘‘‘ 数据库查询 ‘‘‘
try:
self.cursor.execute(sql) # 返回 查询数据 条数 可以根据 返回值 判定处理结果
data = self.cursor.fetchall() # 返回所有记录列表
print(data)
# 结果遍历
for row in data:
name = row["name"]
age = row["age"]
# 遍历打印结果
print(‘age = %s, name = %s‘ % (age, name))
except:
print(‘Error: unable to fetch data‘)
finally:
self.cursor.close()
def closeDb(self):
‘‘‘ 数据库连接关闭 ‘‘‘
self.db.close()
if __name__ == ‘__main__‘:
DbHandle = DataBaseHandle(‘127.0.0.1‘, ‘root‘, ‘123456‘, ‘mysql6_3‘, 3306, )
# DbHandle.insertDB("insert into students (name,age) values (‘王小欢‘,19)")
# DbHandle.deleteDB("delete from students where name=‘随便起名‘")
DbHandle.no_select_info("update students set name=‘王欢‘ where id=4")
# DbHandle.selectDb("select * from students")
DbHandle.closeDb()
使用pymysql链接数据库