如何使用pip安装Python的MySQLdb模块?


当前回答

转到pycharm,然后转到默认设置——> pip(双击)——pymsqldb..——> install——在像这样的程序中安装使用之后

import pymysql as MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root","test" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("show tables")

# Fetch a single row using fetchone() method.
data = cursor.fetchall()
print (data)

# disconnect from server
db.close()

其他回答

我也有同样的问题。如果您使用的是Windows,请遵循这些步骤。 至: 1.我的电脑 2.系统属性 3.系统高级设置 4. 在“高级”选项卡下单击“环境变量”按钮 5. 然后在“系统变量”下,您必须添加/更改以下变量:PYTHONPATH和Path。下面是我的变量的粘贴: python路径:

C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts

路径:

C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts

参考这个链接

你可以去这个网站下载软件包。

我的环境是:

Windows 10 Pro, Python 3.7 (Python -3.7.1-amd64.exe) MySQL 8.0 (MySQL -install -web-community-8.0.13.0 msi)

PIP安装mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl

对我有用。

import MySQLdb, sys


# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
    db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
    print ("Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit()

# Creating cursor 
cursor = db.cursor()

这招对我很管用:

pip install mysqlclient

这是针对python 3.x的

PIP安装mysql-connector-python 如文档中所述:

https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html