python连接数据库

  1 import MySQLdb
  2 # 导入 MySQL 库
  3 
  4 class MysqlMethod(object):
  5     def __init__(self):
  6         # 前提:能够连接上数据库
  7         self.get_connect()
  8     
  9 
 10     def get_connect(self):
 11         # 获取连接
 12         try:
 13             self.conn = MySQLdb.connect(
 14             host = '127.0.0.1',
 15             # 主机
 16             user = 'root',
 17             # 用户名
 18             passwd = 'root',
 19             # 密码
 20             db = 'python_prac',
 21             # 数据库
 22             port = 3306,
 23             # 端口号
 24             charset = 'utf8'
 25             # 避免字符编码问题
 26         )
 27         except MySQLdb.Error as e:
 28             print("连接数据库时,出现错误") 
 29             print("错误信息如下:
 %s"%e)
 30         else:
 31             print("连接 MySQL 成功!")
 32 
 33 
 34     def close_connect(self):
 35         # 关闭连接
 36         try:
 37             # 关闭连接
 38             self.conn.close()
 39             # 关闭数据库连接
 40         except MySQLdb.Error as e:
 41             print("关闭数据库时出现错误")
 42             print("错误信息如下:
 %s"%e)
 43         else:
 44             print("退出成功,欢迎下次使用!")
 45     
 46 
 47     def get_onedata(self):
 48         # 获取一条数据
 49         cursor = self.conn.cursor()
 50         # 获取游标
 51         sql = 'select * from students where age between %s and %s'
 52         # 查询语句
 53         cursor.execute(sql,(15,25))
 54         # execute(语句,(参数))
 55         result = dict(zip([k[0] for k in cursor.description],cursor.fetchone()))
 56         '''
 57             zip(列表推导式,获取到的值)
 58             字典的键:描述数据的值
 59             字典的值:获取到的值
 60             例:
 61                 lst_keys = ['a','b','c']
 62                 lst_values = [1,2,3]
 63                 dict(zip(lst_keys,lst_values))
 64             得到的结果:
 65                 {'a': 1, 'b': 2, 'c': 3}
 66         '''
 67         # 元组类型转换为字典,便于通过索引查找数据
 68         print("获取到一条数据:")
 69         return result
 70 
 71     def get_moredata(self,page,page_size):
 72         # 添加多条数据
 73         offset = (page - 1) * page_size
 74         # 起始位置
 75         cursor = self.conn.cursor()
 76         sql = 'select * from students where age between %s and %s limit %s,%s;'
 77         cursor.execute(sql,(15,45,offset,page_size))
 78         result = list(dict(zip([k[0] for k in cursor.description],row)) for row in cursor.fetchall())
 79         '''
 80 
 81             使用 zip 将 列名 和 获取到的数据 压缩为一个个单独的二元组
 82                 但类型为 <class 'zip'> 需要进行转换才能看到具体的值
 83                 zip([k[0] for k in cursor.description],row)
 84                     ('id', 1)···
 85             使用 dict 将 zip 类型转换为字典类型
 86                 dict(zip([k[0] for k in cursor.description],row))
 87                     {'id': 1,···}
 88             使用 列表推导式 将每一个 row 变为查找到的多个数据中的一个
 89                 原理:[元素操作 for 元素 in 序列对象]
 90                 list -> []
 91                 list[ row 的操作 for row in 数据集]
 92         '''
 93         print("获取到多条数据:")
 94         # result 为[{},{}] 形式
 95         return result
 96 
 97     def insert_onedata(self):
 98         # 添加一条数据
 99         try:
100             sql = "insert into stu_0415(name,school) values (%s,%s);"
101             # 查询语句
102             cursor = self.conn.cursor()
103             # 获取游标
104             need_info = ('王五','厦大')
105             # 需要插入的数据
106             cursor.execute(sql,need_info)
107             # 运行 sql 语句
108             self.conn.commit()
109             # 提交,如果没有提交,数据库数据不会发生变化
110         except :
111             print("插入数据失败")
112             self.conn.rollback()
113             # 如果个别数据插入成功了,则也不算入数据库
114         print("插入数据成功")
115 
116 def main():
117     sql_obj = MysqlMethod()
118     # 创建一个 sql 对象
119     data = sql_obj.get_onedata()
120     # 获取一条数据
121     print(data)
122 
123     moredata = obj.get_moredata(1,5)
124     # 查看 0~5 的数据
125     for item in moredata:
126         print(item)
127         # 循环遍历输出字典对象
128         print("-------------")
129     obj.insert_onedata()
130     # 插入一条数据
131 
132 if __name__ == '__main__':
133     main()
134     # 运行主程序

2020-04-15

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12704539.html