我是靠谱客的博主 活力摩托,这篇文章主要介绍python入门二(数据库操作),现在分享给大家,希望可以做个参考。

python对数据库的支持很多比如小的有sqllite、大的服务关系型数据库 mysql、非关系型数据库mongodb等,这里我们就来看看python和mysql的适配使用,本人安装的python是3.6版本的所以使用的是pymysql模块,具体安装在第一篇文章中有哦……

下面来看看代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import pymysql from test.test_robotparser import PasswordProtectedSiteTestCase #dicts dbdict={"testdb":{"host":"127.0.0.1","port":3306,"user":"root","passwd":"admin","db":"test","charset":"utf-8"}, "userdb":{"host":"127.0.0.1","port":3306,"user":"root","passwd":"admin","db":"user","charset":"utf-8"}} class dball(object): def __init__(self,name,dicts): self.name= name self.host=dicts["host"] self.port =dicts["port"] self.user =dicts["user"] self.passwd =dicts["passwd"] self.db =dicts["db"] self.charset = dicts["charset"] print("init complete") def getConnection(self): cnx = pymysql.connect(host=self.host,port =self.port,user=self.user,passwd=self.passwd,db=self.db) return cnx def getDicCursor(self,cnx): cursor = cnx.cursor(pymysql.cursors.DictCursor) return cursor def getCursor(self,cnx): cursor = cnx.cursor() return cursor def closeCursor(self,cursor): if cursor is not None: cursor.close() print(str(self.name)+" cursor is closed") return True elif cursor is None: print(str(self.name)+" cursor is None") return True else : print(str(self.name)+" cursor close failed") return False def closeCnx(self,cnx): if cnx is not None: cnx.close() print(str(self.name)+" cnx is closed") return True elif cnx is None: print(str(self.name)+" cnx is None") else: print(str(self.name)+" cnx closed failed") return False def queryDic(self,sqls,cursor): len = cursor.execute(sqls) result = cursor.fetchall() self.closeCursor(cursor) mydicts={"len":len,"result":result} return mydicts def chancelResult(self,dict): if dict is not None: nameList =[] for res in dict: name = res["name"] nameList.append(str(name)) count =nameList.count("110") print("count: "+str(count)) elif dict is None: print(str(self.name)+" result is none") else: print("want to do ?") if __name__ =="__main__": dbtest1 = dball("dbtest1",dbdict["userdb"]) con = dbtest1.getConnection() cursor =dbtest1.getDicCursor(con) sql ="SELECT id,name FROM user" dictresult = dbtest1.queryDic(sql, cursor) len = dictresult["len"] result =dictresult["result"] dbtest1.chancelResult(result) print("len:"+str(len) +" result:"+str(result) ) print("query end") dbtest1.closeCnx(con)

运行结果:

复制代码
1
2
3
4
5
6
7
init complete dbtest1 cursor is closed count: 3 len:13 result:[{'id': '1', 'name': '12'}, {'id': '110', 'name': '110'}, {'id': '1101', 'name': '110'}, {'id': '1102', 'name': '110'}, {'id': '120', 'name': '120'}, {'id': '121', 'name': '121'}, {'id': '122', 'name': '122'}, {'id': '124', 'name': '124'}, {'id': '125', 'name': '125'}, {'id': 'whd1', 'name': 'whd1'}, {'id': 'whd2', 'name': 'whd2'}, {'id': 'whd3', 'name': 'whd3'}, {'id': 'whd5', 'name': 'whd5'}] query end dbtest1 cnx is closed

ok 下面来看看代码中的知识点:

1、首先定义了一个dbdict 字典,该字典中保存了我们可能用到的数据库相关信息

2、定义了一个dball类,这个类中包括了数据库相关的所有方法

3、 dbtest1 = dball("dbtest1",dbdict["userdb"]) 创建类实例,第一个参数是该实例的name属性的值第二个值也是我们定义的字典中数据库的信息,这样__init()__方法就会被自动执行而给实例的各个属性赋值即host 、port、use 、passwd、db等

4、 con = dbtest1.getConnection() 调用对象的方法获取数据库链接,具体是使用了pymysql.connect()方法来实现。

5、cursor =dbtest1.getDicCursor(con) 获取游标,你可能看到了有两种获取游标的方法,其中一种是字典型的而另一种就是元组型的,这个和查询出来的结果是有关的,两种的结果格式就是一种是字典型的而另一种就是元组如下:

result:[{'id': '1', 'name': '12'}, {'id': '110', 'name': '110'}, {'id': '1101', 'name': '110'}]

result:(('1', '12'), ('110', '110'), ('1101', '110'))

ok这就是两种格式

6、 dictresult = dbtest1.queryDic(sql, cursor) 拿着游标去查询,具体的查询也是使用游标提供的 cursor.execute(sqls)方法来执行。

result = cursor.fetchall() 来获取查询到的所有数据

7、处理结果方法,遍历查询结果进行一些统计计算……




最后

以上就是活力摩托最近收集整理的关于python入门二(数据库操作)的全部内容,更多相关python入门二(数据库操作)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部