为Windows下python2.7安装MySQLdb模块

根据Python多少位下载对应版本:

32位:https://pypi.python.org/pypi/MySQL-python/1.2.5

64位:http://arquivos.victorjabur.com/python/modules/MySQL-python-1.2.3.win-amd64-py2.7.exe

下载对应版本,直接安装。

输入代码测试:

 
  1. import MySQLdb  
  2.   
  3. #-----------MySQL测试代码-------------  
  4.   
  5. def mysql_test():  
  6.     try:  
  7.         sql='select * from student'  
  8.         conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='test',db='test',port=3306)  
  9.         cur=conn.cursor()  
  10.         cur.execute(sql)  
  11.         print 'conn:%s' %conn  
  12.         print 'cur: %s' %cur  
  13.         cur.close()  
  14.         conn.close()  
  15.     except MySQLdb.Error,e:  
  16.         print 'MySQL Error %d:%s' %(e.args[0],e.args[1])  
  17.   
  18. if __name__=="__main__":  
  19.     mysql_test()  
测试结果显示连接成功:
 
  1. conn:<_mysql.connection open to '127.0.0.1' at 2d01b28>  
  2. cur: <MySQLdb.cursors.Cursor object at 0x00000000031F9EF0>  
如果显示如下错误,应该改localhost为127.0.0.1.
 
  1. MySQL Error 2013:Lost connection to MySQL server at 'waiting for initial communication packet', system error: 0   
 
 
posted @ 2017-10-08 15:46  sjfgod  阅读(8711)  评论(0编辑  收藏  举报