python连接数据库实例
复制代码
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# encoding: utf-8 import MySQLdb #数据库连接实现类 class DbConnection(object): def __init__(self): # 当前类的实例 self.conn = None def open(self): child = type(self) # child ---> <class '__main__.DbBi'> print child if self.conn is None: self.conn = MySQLdb.connect( host=child.host, port=child.port, user=child.user, passwd=child.passwd, db=child.db, charset="utf8" ) return self.conn class DbBi(DbConnection): host = '127.0.0.1' port = 3306 user = 'root' passwd = '123456' db = 'me' def find_Student(): # db = MySQLdb.connect('localhost', 'root', '980523', 'me', charset='utf8') db = DbBi().open() cursor = db.cursor() cursor.execute("SET NAMES UTF8") sql = """ select * from student ;""" cursor.execute(sql) print sql results = cursor.fetchall() # 获取所有查询结果 cursor.close() db.close() return results def main(): data = find_Student() # print type(data) #data 数据类型 # for i in list(data): # print i print str(data).decode('unicode_escape') # unicode转中文 if __name__ == '__main__': main()
python中self 理解 self 即Instance本身。
Python中规定好了,函数的第一个参数,就必须是实例对象本身,并且建议,约定俗成,把其名字写为self
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14# encoding: utf-8 class Student(object): def __init__(self, name, age): self.name = name self.age = age print ('self: ', self) print ('name', self.name) print ('type of self: ', type(self)) p = Student('jack', 18)
运行结果:
最后
以上就是儒雅母鸡最近收集整理的关于python连接数据库的全部内容,更多相关python连接数据库内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复