python操作mysql

之前一直C++連數據庫,略顯笨重,最近主題就是黑C++,python操作mysql還是比較方便的。

我用的windows32位,直接安裝的編譯好MySQLdb,下載地址http://www.codegood.com/downloads

import MySQLdb ok就安裝成功了。

#coding=utf-8
#!/usr/bin/env python

import MySQLdb

conn = MySQLdb.connect(host='your ip',user='xxx',passwd='***')
cursor = conn.cursor()
count = cursor.execute("""show databases""")
print 'database num:%d' %count
for x in cursor:
    print x
conn.select_db('test')
count = cursor.execute("select * from test")
print 'records num:%d' %count
result = cursor.fetchone()
print result
result = cursor.fetchmany(2)
for r in result:
    print r
cursor.close()

開始遇到DeprecationWarning: the sets module is deprecated這個問題,參考http://blog.sina.com.cn/s/blog_70aa69580100oi41.html

解決辦法:
找到Python26\lib\site-packages\MySQLdb下的__init__.py文件
1) 在文件中 "__init__", 註釋掉:
from sets import ImmutableSet
class DBAPISet(ImmutableSet):
新增:
class DBAPISet(frozenset):

2) 在文件中"converters.py", 註釋掉  from sets importBaseSet, Set 這一句話。

3) 在文件中"converters.py", 修改 "Set" 成爲 "set" ( 只有兩個地方需要修改):
大概 line 48: return Set([ i for i in s.split(',') if i ]) 改爲 return set([ i for i in s.split(',') if i ])

大概 line 128: Set: Set2Str 改爲 set: Set2Str

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章