forked from shibing624/python-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_db.py
More file actions
62 lines (51 loc) · 1.67 KB
/
select_db.py
File metadata and controls
62 lines (51 loc) · 1.67 KB
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
# -*- coding: utf-8 -*-
"""
@author:XuMing([email protected])
@description:
"""
import pymysql
def normal_str(text):
return text.replace('\'', '\\\'')
class DB(object):
def __init__(self, host="", user_name="", user_password="", db_name="", port=3306, charset='utf8'):
self.host = host
self.user_name = user_name
self.user_password = user_password
self.db_name = db_name
self.port = port
self.charset = charset
self.is_inited = False
def init(self):
# 打开数据库连接
self.db = pymysql.connect(self.host, self.user_name, self.user_password, self.db_name, charset=self.charset,
port=self.port)
self.is_inited = True
def check_init(self):
if not self.is_inited:
self.init()
def exe(self):
self.check_init()
# 使用cursor()方法获取操作游标
cursor = self.db.cursor()
# SQL语句
sql = "SELECT id, name from test"
count = 0
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
# 打印结果
print("id=%s,name=%s" % (id, name))
count += 1
except Exception as e:
print("Error: unable to fetch data", e)
print("[Info]已查询到%d条数据" % count)
# 关闭数据库连接
self.db.close()
if __name__ == "__main__":
my_db = DB("180.76.120.65", "root", "", "mm_images", port=3306)
my_db.exe()