如何使用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()

其他回答

我尝试了所有的选项,但不能让它在红帽平台上工作。 我做了下面的工作:-

yum install MySQL-python -y

一旦包被安装,就可以在解释器中导入模块如下

>>> import MySQLdb
>>> 

这很容易,但很难记住正确的拼写:

pip install mysqlclient

如果你需要1.2。x版本(仅适用于遗留的Python),使用pip安装MySQL-python

注意:在运行上述命令时,有些依赖项可能必须就位。一些关于如何在不同平台上安装这些工具的提示:

Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie)

sudo apt-get install python-pip python-dev libmysqlclient-dev

Fedora 24:

sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc

苹果操作系统

brew install mysql-connector-c

如果失败了,那就试试

brew install mysql

转到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 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()

上面的答案很好,但是在Windows中使用pip安装MySQL-python时可能会出现一些问题

例如,它需要一些与Visual Stdio相关的文件。一个解决方案是安装VS2008或2010......显然,它花费太多。

另一种方法是@bob90937的答案。我是来补充的。

通过http://www.lfd.uci.edu/~gohlke/pythonlibs,你可以下载许多科学开源扩展包的Windows二进制文件,用于Python编程语言的官方CPython发行版。

回到主题,我们可以选择MySQL-python(py2)或Mysqlclient(py3)并使用pip install进行安装。它给我们很大的方便!