今天想把我的Python的抓取器和MYSQL连在一块用,折腾了很久,也Google了些资料,为以防今后又会哟重复一次,特地把调试的步骤log down (最近记性不行,常常一天吃5,6顿饭,唉~~)
1. 下载MYSQL >> 这个就不多说了,从SUN网站down就行了,如果你想要个可视化的工具,你可以安装Navicat或者直接来个MSQL GUI
2. 下载MYSQL FOR PATHON edition , 由于我是X86 32的 WIN系统,就按此安装。
3. 如果你的%PYTHON_HOME%/lib 下发现MySQLdb目录,那就证明你第一步安装成功。
4. 接下来,打开你的CMD窗口,enter python >> help(MYSQLdb), 你估计会看到
File "C:\Python26\lib\site-packages\MySQLdb\__init__.py", line 19, in
ImportError: DLL load failed: 找不到指定的模块。
这个时候就该google了,后来发现是缺少了2个dll文件分别为 libguide40.dll和libmmd.dll(See attachment)
把这两个zip包解压后拷贝到/WINDOWS/SYSTEM32目录
5. 再敲help(MYSQLdb), 靠,又错了
sys:1: DeprecationWarning: the sets module is deprecated
再google一把,原来是python 2.6 找不到sets,
- 找到 %PYTHON_HOME%/lib/MySQLdb文件夹的中__init__.py,注释掉 from sets import ImmutableSet 和
- 将下一行 class DBAPISet(ImmutableSet): 修改成 class DBAPISet(frozenset):
- 找到converters.py注释掉from sets import BaseSet, Set
- 修改第45行和129行中的Set为set
6. 喝口水,再再敲help(MYSQLdb), 靠~~~~~ help 信息出来了,大概好了吧,于是马上的动手写段代码
'''
Created on 2009-9-13
@author: Administrator
'''
#encoding=utf-8
import MySQLdb
import sys
import random
class MYSQLTest:
def __init__(self, host, username, password, schema, table):
self.host = host
self.username = username
self.password = password
self.schema = schema
self.table = table
#
def doConnect(self):
conn = MySQLdb.Connection(self.host, self.username, self.password, self.schema)
return conn;
def doClose(self):
print "do CLose"
#
def doSelect(self):
self.conn = self.doConnect()
cur = self.conn.cursor()
cur.execute('select * from ' + self.table + '')
results = cur.fetchall()
for i in results:
print str(i)
cur.close()
self.doClose()
# Insert Test
def doInsert(self):
self.conn = self.doConnect()
cur = self.conn.cursor()
id = random.randint(0, 500)
print id
sql = 'insert into ' + self.schema + '.' + self.table + ' values(' + str(id) + ', \'test\')'
print "SQL " + sql
cur.execute(sql)
self.conn.commit()
#cur.insert_id()
cur.close()
self.doClose()
# Update
def doUpdate(self):
self.conn = self.doConnect()
print "TODO UPDATE"
cur = self.conn.cursor()
cur.execute('update ' + self.schema + '.' + self.table + ' set info=(\'test\') where id > 3')
self.conn.commit()
cur.close()
self.doClose()
# Delete
def doDelete(self):
self.conn = self.doConnect()
print "TODO DELETE"
cur = self.conn.cursor()
cur.execute('delete from ' + self.schema + '.' + self.table + ' where id < 100')
self.conn.commit()
cur.close()
self.doClose()
#def
if __name__ == '__main__':
print "Test MYSQL"
# Insert
try:
mySQL = MYSQLTest('localhost', 'root', 'pass', 'python_test', 'py_test')
mySQL.doSelect()
#mySQL.doSelect()
mySQL.doInsert()
#mySQL.doSelect()
mySQL.doUpdate()
mySQL.doDelete()
mySQL.doSelect()
except:
print "Exception Happen"
pass
唉 ~~ 总算行了,2个小时就这个去了。