如何为mysql获取正确版本的python模块

时间:2015-10-28 23:58:06

标签: mysql python-3.3

我正在尝试使用python连接到mysql数据库,但是我找不到正确的连接器和名为MySQLdb的模块,我怎样才能找到正确的源代码? 当我导入模块时,它显示这样的错误,因为我没有添加正确的模块

>>> import MySQLdb
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
import MySQLdb
ImportError: No module named 'MySQLdb'
ImportError: No module named 'sqlobject'
>>> 

1 个答案:

答案 0 :(得分:1)

https://github.com/PyMySQL/PyMySQL/下载模块将解压缩的文件复制到python中的lib文件夹,然后编写以下代码

import pymysql

hostname = 'localhost'
username = 'username'
password = 'password'
database = 'db_name'

# Simple routine to run a query on a database and print the results:
def doQuery( conn ) :
  cur = conn.cursor()

  cur.execute( "SELECT col1, col2 FROM table_name" )

  for column1, column2 in cur.fetchall() :
    print(column1, column2)

print ("Using pymysql…")
myConnection = pymysql.connect( host=hostname, user=username,passwd=password, db=database )
doQuery( myConnection )
myConnection.close()