在用Python操作MySQL数据库之前,需先安装第三方库,我这里用的是pymysql:

pip install pymysql

还有其他第三方库如:mysqldb。可以在官网下载:https://pypi.org/  

 

 1 # coding=utf-8
 2 import pymysql
 3 
 4 class Mysql_search():
 5     def __init__(self):
 6         try:
 7             self.conn = pymysql.connect(host="192.168.1.86",
 8                                    user="root",
 9                                    password="pwd123",
10                                    db="TEST",
11                                    charset="utf8")
12 
13             self.cursor = self.conn.cursor()
14         except pymysql.err as e:
15             print("error" % e)
16 
17     def get_one(self):
18         sql = "select * from api_test where method = %s order by id desc"
19         self.cursor.execute(sql, ('post',))
20         # print(dir(self.cursor))
21         # print(self.cursor.description)
22         # 获取第一条查询结果,结果是元组
23         rest = self.cursor.fetchone()
24         # 处理查询结果,将元组转换为字典
25         result = dict(zip([k[0] for k in self.cursor.description], rest))
26         self.cursor.close()
27         return result
28 
29     def get_all(self):
30         sql = "select * from api_test where method = %s order by id desc"
31         self.cursor.execute(sql, ('post',))
32         # 获取第一条查询结果,结果是元组
33         rest = self.cursor.fetchall()
34         # 处理查询结果,将元组转换为字典
35         result = [dict(zip([k[0] for k in self.cursor.description], row)) for row in rest]
36         self.cursor.close()
37         return result
38 
39     def db_close(self):
40         self.conn.close()
41 
42 
43 if __name__ == '__main__':
44     obj = Mysql_search()
45     # result = obj.get_one()
46     # print(result)
47     # print(result['url'])
48     reslt = obj.get_all()
49     for item in reslt:
50         print(item)
51         print("-"*10)
52     obj.db_close()