ZheX Blog Idea来源于生活的经验

23八/090

Windows 下 python 连接 mysql 问题

在windows要让python能链接到mysql需要为添加正确的驱动, 我们可以通过 http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe 下载 for python 2.6 的mysql驱动。

接下来让我们写一段测试代码看看是不是已经可以正确连接了:

import MySQLdb
db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
print names
db.close()

如果在import MySQLdb的时候出现下面的提示错误:

'deprecation warning': 
C:\Python\lib\site-packages\MySQLdb\__init__.py:34: 
DeprecationWarning: the sets module is deprecated 
from sets import ImmutableSet

那我们试着改写类库文件:

1) 打开 "__init__", 替换:
from sets import ImmutableSet
class DBAPISet(ImmutableSet):
改为
class DBAPISet(frozenset)

2) 打开"converters.py", 删除:
from sets import BaseSet, Set

3) 在"converters.py" 文件中把 "Set" 替换成 "set" (IMPORTANT: 有两处需要修改):
line 48: return set([ i for i in s.split(',') if i ])
line 128: set: Set2Str,