python 连接mysql 时,connect 出现错误,怎么解决

2024-11-15 13:32:25
推荐回答(2个)
回答1:

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
77
78
79

# -*- coding: utf-8 -*-
import MySQLdb
from MySQLdb.cursors import DictCursor

def catch_2006(func):
"""
To catch MySQL Error 2006 ('Server has gone away')
"""

def _(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except MySQLdb.Error, e:
print __file__, e
if e.args[0] == 2006 or e.args[0] == 0:
self.reboot_conn()
return func(self, *args, **kwargs)
# todo
# How to deal if not the code

return _

class DB(object):
def __init__(self, host, port, user,
passwd, db, use_unicode=True, charset='utf8'):
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.db = db
self.use_unicode = use_unicode
self.charset = charset

@property
def conn(self):
if not hasattr(self, '__conn'):
self.__conn = MySQLdb.connect(
host=self.host,
port=self.port,
user=self.user,
passwd=self.passwd,
db=self.db,
use_unicode=self.use_unicode,
charset=self.charset
)
return self.__conn

def reboot_conn(self):
if hasattr(self, '__conn'):
try:
self.__conn.close()
del self.__conn
except:
pass

@catch_2006
def query(self, sql, args=None):
print sql
cursor = self.conn.cursor()
cursor.execute(sql, args)
cursor.execute('commit')
cursor.close()

@catch_2006
def select(self, sql, args=None, is_dict=False, is_one=False):
# print sql, args
if is_dict:
cursor = self.conn.cursor(cursorclass=DictCursor)
else:
cursor = self.conn.cursor()
cursor.execute(sql, args)
if is_one:
resultset = cursor.fetchone()[0]
else:
resultset = cursor.fetchall()
cursor.close()
return resultset

这个是我以前项目中使用python链接mysql的例子,你可以参考一下。

回答2:

得看具体是扫描错误啊。