标签归档:mysql

在Windows中将MySQL与Python集成

问题:在Windows中将MySQL与Python集成

我发现在Windows系统中很难将MySQL与Python结合使用。

我目前正在使用Python 2.6。我试图使用提供的安装脚本来编译MySQL-python-1.2.3b1(应该适用于Python 2.6吗?)源代码。安装脚本将运行,并且不会报告任何错误,但不会生成_mysql模块。

我也尝试过为Python 2.5设置MySQL,但没有成功。使用2.5的问题是Python 2.5是使用Visual Studio 2003编译的(我使用提供的二进制文件安装了它)。我在Windows系统上安装了Visual Studio 2005。因此setuptools无法生成_mysql模块。

有什么帮助吗?

I am finding it difficult to use MySQL with Python in my windows system.

I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn’t report any error but it doesn’t generate _mysql module.

I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.

Any help ?


回答 0

python-mysqldb的下载页面。该页面包含适用于Python 2.5、2.6和2.7的32位和64位版本的二进制文件。

也有关于消除弃用警告的讨论

更新:这是一个旧的答案。目前,我建议使用PyMySQL。它是纯python,因此它同样支持所有操作系统,几乎是mysqldb的直接替代品,并且还可以与python 3一起使用。最好的安装方法是使用pip。您可以从这里安装它(更多说明在此处),然后运行:

pip install pymysql

Download page for python-mysqldb. The page includes binaries for 32 and 64 bit versions of for Python 2.5, 2.6 and 2.7.

There’s also discussion on getting rid of the deprecation warning.

UPDATE: This is an old answer. Currently, I would recommend using PyMySQL. It’s pure python, so it supports all OSes equally, it’s almost a drop-in replacement for mysqldb, and it also works with python 3. The best way to install it is using pip. You can install it from here (more instructions here), and then run:

pip install pymysql

回答 1

这可能听起来像您的爷爷给我的建议,但是这里的所有答案都没有提到最好的方法:去安装ActivePython而不是python.org Windows二进制文件。很长一段时间以来,我真的想知道为什么在Windows上进行Python开发如此之薄-直到安装了activestate python。我不隶属于他们。这只是简单的事实。写在每堵墙上:Windows上的Python开发= ActiveState!然后您就可以pypm install mysql-python正常工作了。没有编译狂欢。没有奇怪的错误。没有恐怖。五分钟后就可以开始编码并进行实际工作。这是在Windows上运行的唯一方法。真。

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita – until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.


回答 2

随着Python新手学习Python生态系统,我已经完成了这一步。

  1. 安装setuptools 说明

  2. 安装MySQL 5.1。从此处下载97.6MB MSI 您不能使用Essentials 版本,因为它不包含C库。
    确保选择一个自定义安装,并标记要安装的开发工具/库,因为默认情况下未完成安装。这是获取C头文件所必需的。
    您可以通过在安装目录中查找名为“ include”的文件夹来验证您是否已正确完成此操作。EG C:\ Program Files \ MySQL \ MySQL Server 5.1 \ include。它应该有一堆.h文件。

  3. 此处安装Microsoft Visual Studio C ++ Express 2008 这是获取C编译器所必需的。

  4. 以管理员身份打开命令行(右键单击Cmd快捷方式,然后“以管理员身份运行”。请确保打开一个新窗口 安装这些内容否则您的路径将不会更新,并且安装仍将失败。

  5. 在命令提示符下:

    easy_install -b C:\ temp \ sometempdir mysql-python

    那将失败-可以。

    现在,在您的临时目录C:\ temp \ sometempdir中打开site.cfg,并将“ registry_key”设置编辑为:

    Registry_key =软件\ MySQL AB \ MySQL Server 5.1

    现在将CD放入您的临时目录,并:

    python setup.py干净

    python setup.py安装

    您应该准备好摇滚!

  6. 是一个非常简单的脚本,可以根据需要开始为您学习Python DB API。

As Python newbie learning the Python ecosystem I’ve just completed this.

  1. Install setuptools instructions

  2. Install MySQL 5.1. Download the 97.6MB MSI from here You can’t use the essentials version because it doesnt contain the C libraries.
    Be sure to select a custom install, and mark the development tools / libraries for installation as that is not done by default. This is needed to get the C header files.
    You can verify you have done this correctly by looking in your install directory for a folder named “include”. E.G C:\Program Files\MySQL\MySQL Server 5.1\include. It should have a whole bunch of .h files.

  3. Install Microsoft Visual Studio C++ Express 2008 from here This is needed to get a C compiler.

  4. Open up a command line as administrator (right click on the Cmd shortcut and then “run as administrator”. Be sure to open a fresh window after you have installed those things or your path won’t be updated and the install will still fail.

  5. From the command prompt:

    easy_install -b C:\temp\sometempdir mysql-python

    That will fail – which is OK.

    Now open site.cfg in your temp directory C:\temp\sometempdir and edit the “registry_key” setting to:

    registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1

    now CD into your temp dir and:

    python setup.py clean

    python setup.py install

    You should be ready to rock!

  6. Here is a super simple script to start off learning the Python DB API for you – if you need it.


回答 3

我发现一个人已经成功地为python2.6构建了mysql,并共享了链接,网址为http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

…您可能会在导入MySQLdb时看到警告,这很正常,不会造成任何伤害,

C:\ Python26 \ lib \ site-packages \ MySQLdb__init __。py:34:DeprecationWarning:sets模块已从set import ImmutableSet中弃用

I found a location were one person had successfully built mysql for python2.6, sharing the link, http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

…you might see a warning while import MySQLdb which is fine and that won’t hurt anything,

C:\Python26\lib\site-packages\MySQLdb__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet


回答 4

pymysql呢?它是纯Python,我已经在Windows上成功使用了它,绕过了编译和安装mysql-python的困难。

What about pymysql? It’s pure Python, and I’ve used it on Windows with considerable success, bypassing the difficulties of compiling and installing mysql-python.


回答 5

您不是唯一遇到Python 2.6和MySQL问题的人(http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/) 。这是说明如何在Python 2.5下运行的方法http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/ 祝您好运

You’re not the only person having problems with Python 2.6 and MySQL (http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/). Here’s an explanation how it should run under Python 2.5 http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/ Good luck


回答 6


回答 7

http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python上的预编译二进制文件仅对我有用。

  1. 打开 MySQL_python-1.2.5-cp27-none-win_amd64.whl使用zip提取程序文件。
  2. 将内容复制到 C:\Python27\Lib\site-packages\

The precompiled binaries on http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python is just worked for me.

  1. Open MySQL_python-1.2.5-cp27-none-win_amd64.whl file with zip extractor program.
  2. Copy the contents to C:\Python27\Lib\site-packages\

回答 8

在Python 3.4上,我已经从http://www.lfd.uci.edu/~gohlke/pythonlibs/安装了mysqlclient,并使用pip install mysqlclient进行了安装。

On Python 3.4 I’ve installed mysqlclient from http://www.lfd.uci.edu/~gohlke/pythonlibs/ with pip install mysqlclient and it’s working.


回答 9

您可以尝试使用myPySQL。真的很容易使用;Windows无需编译,即使您出于任何原因需要对其进行编译,也只需要安装Python和Visual C(而不是mysql)。

http://code.google.com/p/mypysql/

祝好运

You can try to use myPySQL. It’s really easy to use; no compilation for windows, and even if you need to compile it for any reason, you only need Python and Visual C installed (not mysql).

http://code.google.com/p/mypysql/

Good luck


回答 10

因为我在(pylons / pyramid)virtualenv中运行python,所以无法(有效地)运行以前链接的二进制安装程序。

我在执行Willie的回答步骤时遇到问题,但我确定问题是(可能)我正在运行Windows 7 x64 install,这将mysql的注册表项放在稍有不同的位置,特别是在我的情况下(请注意:正在运行5.5版):“ HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ MySQL AB \ MySQL Server 5.5”。

但是,路径中不能包含“ HKEY_LOCAL_MACHINE \”,否则它将失败。

另外,我必须在步骤3和4之间重新启动。

在完成所有这些工作之后,IMO可以从cygwin运行整个python dev环境会更聪明。

Because I am running python in a (pylons/pyramid) virtualenv, I could not run the binary installers (helpfully) linked to previously.

I had problems following the steps with Willie’s answer, but I determined that the problem is (probably) that I am running windows 7 x64 install, which puts the registry key for mysql in a slightly different location, specifically in my case (note: I am running version 5.5) in: “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MySQL AB\MySQL Server 5.5”.

HOWEVER, “HKEY_LOCAL_MACHINE\” cannot be included in the path or it will fail.

Also, I had to do a restart between steps 3 and 4.

After working through all of this, IMO it would have been smarter to run the entire python dev environment from cygwin.


回答 11

如果您正在寻找Python 3.2,这似乎是我到目前为止找到的最佳解决方案

资料来源:http : //wiki.python.org/moin/MySQL

If you are looking for Python 3.2 this seems the best solution I found so far

Source: http://wiki.python.org/moin/MySQL


回答 12

您可能还想考虑使用Cygwin,它在存储库中具有mysql python库。

You might want to also consider making use of Cygwin, it has mysql python libraries in the repository.


回答 13

您还可以将pyodbcMySQL Connector / ODBC一起使用,以在Windows上使用MySQL。 Unixodbc也可用于使代码在Linux上兼容。Pyodbc使用标准的Python DB API 2.0,因此如果您坚持要在MySQL / PostgreSQL / SQLite / ODBC / JDBC驱动程序等之间进行切换,应该会比较轻松。

You can also use pyodbc with the MySQL Connector/ODBC to use MySQL on Windows. Unixodbc is also available to make the code compatible on Linux. Pyodbc uses the standard Python DB API 2.0 so if you stick with that switching between MySQL/PostgreSQL/SQLite/ODBC/JDBC drivers etc. should be relatively painless.


回答 14

赞成itsadok的答案,因为它也使我也安装了python 2.7,该软件位于:http : //www.codegood.com/archives/129

upvoted itsadok’s answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129


回答 15

厌倦了MySQLdb的安装问题,而是尝试了pymysql

易于安装;

git clone https://github.com/petehunt/PyMySQL.git
python setup.py install

API几乎相同。

Got sick of the installation troubles with MySQLdb and tried pymysql instead.

Easy setup;

git clone https://github.com/petehunt/PyMySQL.git
python setup.py install

And APIs are pretty much the same.


如何从SQLAlchemy表达式获取原始的编译SQL查询?

问题:如何从SQLAlchemy表达式获取原始的编译SQL查询?

我有一个SQLAlchemy查询对象,想要获取已绑定所有参数的已编译SQL语句的文本(例如,否%s或其他变量正等待语句编译器或MySQLdb方言引擎的绑定等)。

调用str()查询将显示如下内容:

SELECT id WHERE date_added <= %s AND date_added >= %s ORDER BY count DESC

我试着在query._params中查找,但这是一个空字典。我使用装饰器的这个示例sqlalchemy.ext.compiler.compiles编写了自己的编译器,但即使那里的语句仍然有%s我想要的数据。

我无法弄清楚何时混入参数来创建查询。在检查查询对象时,它们始终是一个空字典(尽管查询执行得很好,并且当您打开echo记录时引擎会打印出来)。

我开始收到消息,SQLAlchemy不想让我知道底层查询,因为它破坏了表达式API接口的所有不同DB-API的一般性质。我不在乎查询是否在我发现查询之前就已经执行了;我只是想知道!

I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no %s or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).

Calling str() on the query reveals something like this:

SELECT id WHERE date_added <= %s AND date_added >= %s ORDER BY count DESC

I’ve tried looking in query._params but it’s an empty dict. I wrote my own compiler using this example of the sqlalchemy.ext.compiler.compiles decorator but even the statement there still has %s where I want data.

I can’t quite figure out when my parameters get mixed in to create the query; when examining the query object they’re always an empty dictionary (though the query executes fine and the engine prints it out when you turn echo logging on).

I’m starting to get the message that SQLAlchemy doesn’t want me to know the underlying query, as it breaks the general nature of the expression API’s interface all the different DB-APIs. I don’t mind if the query gets executed before I found out what it was; I just want to know!


回答 0

博客提供了更新的答案。

引用博客文章中的内容,这对我来说是建议和有效的。

>>> from sqlalchemy.dialects import postgresql
>>> print str(q.statement.compile(dialect=postgresql.dialect()))

其中q定义为:

>>> q = DBSession.query(model.Name).distinct(model.Name.value) \
             .order_by(model.Name.value)

或者只是任何一种session.query()。

感谢Nicolas Cadou的回答!希望对其他在这里搜索的人有所帮助。

This blog provides an updated answer.

Quoting from the blog post, this is suggested and worked for me.

>>> from sqlalchemy.dialects import postgresql
>>> print str(q.statement.compile(dialect=postgresql.dialect()))

Where q is defined as:

>>> q = DBSession.query(model.Name).distinct(model.Name.value) \
             .order_by(model.Name.value)

Or just any kind of session.query().

Thanks to Nicolas Cadou for the answer! I hope it helps others who come searching here.


回答 1

文档用于literal_binds打印q包含参数的查询:

print(q.statement.compile(compile_kwargs={"literal_binds": True}))

上面的方法有一个警告:仅基本类型(例如int和字符串)才支持该方法,此外,如果直接使用没有预设值的bindparam(),则也不能将其字符串化。

该文档还发出以下警告:

切勿将此技术与从不受信任的输入(例如从Web表单或其他用户输入应用程序)接收到的字符串内容一起使用。SQLAlchemy的将Python值强制转换为直接SQL字符串值的功能对于不受信任的输入是不安全的,并且无法验证传递的数据类型。以编程方式对关系数据库调用非DDL SQL语句时,请始终使用绑定参数。

The documentation uses literal_binds to print a query q including parameters:

print(q.statement.compile(compile_kwargs={"literal_binds": True}))

the above approach has the caveats that it is only supported for basic types, such as ints and strings, and furthermore if a bindparam() without a pre-set value is used directly, it won’t be able to stringify that either.

The documentation also issues this warning:

Never use this technique with string content received from untrusted input, such as from web forms or other user-input applications. SQLAlchemy’s facilities to coerce Python values into direct SQL string values are not secure against untrusted input and do not validate the type of data being passed. Always use bound parameters when programmatically invoking non-DDL SQL statements against a relational database.


回答 2

这应该适用于Sqlalchemy> = 0.6

from sqlalchemy.sql import compiler

from psycopg2.extensions import adapt as sqlescape
# or use the appropiate escape function from your db driver

def compile_query(query):
    dialect = query.session.bind.dialect
    statement = query.statement
    comp = compiler.SQLCompiler(dialect, statement)
    comp.compile()
    enc = dialect.encoding
    params = {}
    for k,v in comp.params.iteritems():
        if isinstance(v, unicode):
            v = v.encode(enc)
        params[k] = sqlescape(v)
    return (comp.string.encode(enc) % params).decode(enc)

This should work with Sqlalchemy >= 0.6

from sqlalchemy.sql import compiler

from psycopg2.extensions import adapt as sqlescape
# or use the appropiate escape function from your db driver

def compile_query(query):
    dialect = query.session.bind.dialect
    statement = query.statement
    comp = compiler.SQLCompiler(dialect, statement)
    comp.compile()
    enc = dialect.encoding
    params = {}
    for k,v in comp.params.iteritems():
        if isinstance(v, unicode):
            v = v.encode(enc)
        params[k] = sqlescape(v)
    return (comp.string.encode(enc) % params).decode(enc)

回答 3

对于MySQLdb后端,我稍微修改了albertov的出色答案(非常感谢!)。我敢肯定,可以将它们合并以检查是否存在comp.positionalTrue但这超出了此问题的范围。

def compile_query(query):
    from sqlalchemy.sql import compiler
    from MySQLdb.converters import conversions, escape

    dialect = query.session.bind.dialect
    statement = query.statement
    comp = compiler.SQLCompiler(dialect, statement)
    comp.compile()
    enc = dialect.encoding
    params = []
    for k in comp.positiontup:
        v = comp.params[k]
        if isinstance(v, unicode):
            v = v.encode(enc)
        params.append( escape(v, conversions) )
    return (comp.string.encode(enc) % tuple(params)).decode(enc)

For the MySQLdb backend I modified albertov’s awesome answer (thanks so much!) a bit. I’m sure they could be merged to check if comp.positional was True but that’s slightly beyond the scope of this question.

def compile_query(query):
    from sqlalchemy.sql import compiler
    from MySQLdb.converters import conversions, escape

    dialect = query.session.bind.dialect
    statement = query.statement
    comp = compiler.SQLCompiler(dialect, statement)
    comp.compile()
    enc = dialect.encoding
    params = []
    for k in comp.positiontup:
        v = comp.params[k]
        if isinstance(v, unicode):
            v = v.encode(enc)
        params.append( escape(v, conversions) )
    return (comp.string.encode(enc) % tuple(params)).decode(enc)

回答 4

事实是,sqlalchemy永远不会将数据与查询混合在一起。查询和数据分别传递到基础数据库驱动程序-数据插值发生在数据库中。

Sqlalchemy如您所见将查询传递str(myquery)给数据库,并且值将进入一个单独的元组。

您可以使用一些方法自己在查询中插入数据(如下面的albertov所建议),但这与sqlalchemy正在执行的事情不同。

Thing is, sqlalchemy never mixes the data with your query. The query and the data are passed separately to your underlying database driver – the interpolation of data happens in your database.

Sqlalchemy passes the query as you’ve seen in str(myquery) to the database, and the values will go in a separate tuple.

You could use some approach where you interpolate the data with the query yourself (as albertov suggested below), but that’s not the same thing that sqlalchemy is executing.


回答 5

首先,让我先说一下,我假设您这样做主要是出于调试目的-我不建议您尝试尝试在SQLAlchemy Fluent API之外修改语句。

不幸的是,似乎没有一种简单的方法可以显示包含查询参数的已编译语句。SQLAlchemy实际上并未将参数放入语句中-它们已作为字典传递给数据库引擎。这使特定于数据库的库可以处理诸如转义特殊字符的操作,以避免SQL注入。

但是您可以很容易地在两步过程中完成此操作。要获取该语句,您可以按照显示的操作进行操作,只需打印查询:

>>> print(query)
SELECT field_1, field_2 FROM table WHERE id=%s;

使用query.statement可以更进一步,以查看参数名称。请注意:id_1下面和%s上面的内容-在这个非常简单的示例中并不是真正的问题,但是在更复杂的语句中可能是关键。

>>> print(query.statement)
>>> print(query.statement.compile()) # seems to be equivalent, you can also
                                     # pass in a dialect if you want
SELECT field_1, field_2 FROM table WHERE id=:id_1;

然后,您可以通过获取params已编译语句的属性来获取参数的实际值:

>>> print(query.statement.compile().params)
{u'id_1': 1} 

至少对MySQL后端有用。我希望它对于PostgreSQL也足够通用,无需使用psycopg2

First let me preface by saying that I assume you’re doing this mainly for debugging purposes — I wouldn’t recommend trying to modify the statement outside of the SQLAlchemy fluent API.

Unfortunately there doesn’t seem to be a simple way to show the compiled statement with the query parameters included. SQLAlchemy doesn’t actually put the parameters into the statement — they’re passed into the database engine as a dictionary. This lets the database-specific library handle things like escaping special characters to avoid SQL injection.

But you can do this in a two-step process reasonably easily. To get the statement, you can do as you’ve already shown, and just print the query:

>>> print(query)
SELECT field_1, field_2 FROM table WHERE id=%s;

You can get one step closer with query.statement, to see the parameter names. Note :id_1 below vs %s above — not really a problem in this very simple example, but could be key in a more complicated statement.

>>> print(query.statement)
>>> print(query.statement.compile()) # seems to be equivalent, you can also
                                     # pass in a dialect if you want
SELECT field_1, field_2 FROM table WHERE id=:id_1;

Then, you can get the actual values of the parameters by getting the params property of the compiled statement:

>>> print(query.statement.compile().params)
{u'id_1': 1} 

This worked for a MySQL backend at least; I would expect it’s also general enough for PostgreSQL without needing to use psycopg2.


回答 6

对于使用psycopg2的Postgresql后端,您可以侦听该do_execute事件,然后使用游标,语句并键入强制参数以及Cursor.mogrify()内联参数。您可以返回True以防止实际执行查询。

import sqlalchemy

class QueryDebugger(object):
    def __init__(self, engine, query):
        with engine.connect() as connection:
            try:
                sqlalchemy.event.listen(engine, "do_execute", self.receive_do_execute)
                connection.execute(query)
            finally:
                sqlalchemy.event.remove(engine, "do_execute", self.receive_do_execute)

    def receive_do_execute(self, cursor, statement, parameters, context):
        self.statement = statement
        self.parameters = parameters
        self.query = cursor.mogrify(statement, parameters)
        # Don't actually execute
        return True

用法示例:

>>> engine = sqlalchemy.create_engine("postgresql://postgres@localhost/test")
>>> metadata = sqlalchemy.MetaData()
>>> users = sqlalchemy.Table('users', metadata, sqlalchemy.Column("_id", sqlalchemy.String, primary_key=True), sqlalchemy.Column("document", sqlalchemy.dialects.postgresql.JSONB))
>>> s = sqlalchemy.select([users.c.document.label("foobar")]).where(users.c.document.contains({"profile": {"iid": "something"}}))
>>> q = QueryDebugger(engine, s)
>>> q.query
'SELECT users.document AS foobar \nFROM users \nWHERE users.document @> \'{"profile": {"iid": "something"}}\''
>>> q.statement
'SELECT users.document AS foobar \nFROM users \nWHERE users.document @> %(document_1)s'
>>> q.parameters
{'document_1': '{"profile": {"iid": "something"}}'}

For postgresql backend using psycopg2, you can listen for the do_execute event, then use the cursor, statement and type coerced parameters along with Cursor.mogrify() to inline the parameters. You can return True to prevent actual execution of the query.

import sqlalchemy

class QueryDebugger(object):
    def __init__(self, engine, query):
        with engine.connect() as connection:
            try:
                sqlalchemy.event.listen(engine, "do_execute", self.receive_do_execute)
                connection.execute(query)
            finally:
                sqlalchemy.event.remove(engine, "do_execute", self.receive_do_execute)

    def receive_do_execute(self, cursor, statement, parameters, context):
        self.statement = statement
        self.parameters = parameters
        self.query = cursor.mogrify(statement, parameters)
        # Don't actually execute
        return True

Sample usage:

>>> engine = sqlalchemy.create_engine("postgresql://postgres@localhost/test")
>>> metadata = sqlalchemy.MetaData()
>>> users = sqlalchemy.Table('users', metadata, sqlalchemy.Column("_id", sqlalchemy.String, primary_key=True), sqlalchemy.Column("document", sqlalchemy.dialects.postgresql.JSONB))
>>> s = sqlalchemy.select([users.c.document.label("foobar")]).where(users.c.document.contains({"profile": {"iid": "something"}}))
>>> q = QueryDebugger(engine, s)
>>> q.query
'SELECT users.document AS foobar \nFROM users \nWHERE users.document @> \'{"profile": {"iid": "something"}}\''
>>> q.statement
'SELECT users.document AS foobar \nFROM users \nWHERE users.document @> %(document_1)s'
>>> q.parameters
{'document_1': '{"profile": {"iid": "something"}}'}

回答 7

以下解决方案使用SQLAlchemy表达式语言并与SQLAlchemy 1.1一起使用。该解决方案不将参数与查询混合(按原始作者的要求),但是提供了一种使用SQLAlchemy模型为不同SQL方言生成SQL查询字符串和参数字典的方法。该示例基于教程http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html

上课了

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class foo(Base):
    __tablename__ = 'foo'
    id = Column(Integer(), primary_key=True)
    name = Column(String(80), unique=True)
    value = Column(Integer())

我们可以使用select函数生成查询语句。

from sqlalchemy.sql import select    
statement = select([foo.name, foo.value]).where(foo.value > 0)

接下来,我们可以将语句编译成查询对象。

query = statement.compile()

默认情况下,该语句使用与SQLite和Oracle等SQL数据库兼容的基本“命名”实现进行编译。如果需要指定方言(例如PostgreSQL),则可以执行

from sqlalchemy.dialects import postgresql
query = statement.compile(dialect=postgresql.dialect())

或者,如果您想将方言明确指定为SQLite,则可以将参数样式从“ qmark”更改为“ named”。

from sqlalchemy.dialects import sqlite
query = statement.compile(dialect=sqlite.dialect(paramstyle="named"))

从查询对象中,我们可以提取查询字符串和查询参数

query_str = str(query)
query_params = query.params

最后执行查询。

conn.execute( query_str, query_params )

The following solution uses the SQLAlchemy Expression Language and works with SQLAlchemy 1.1. This solution does not mix the parameters with the query (as requested by the original author), but provides a way of using SQLAlchemy models to generate SQL query strings and parameter dictionaries for different SQL dialects. The example is based on the tutorial http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html

Given the class,

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class foo(Base):
    __tablename__ = 'foo'
    id = Column(Integer(), primary_key=True)
    name = Column(String(80), unique=True)
    value = Column(Integer())

we can produce a query statement using the select function.

from sqlalchemy.sql import select    
statement = select([foo.name, foo.value]).where(foo.value > 0)

Next, we can compile the statement into a query object.

query = statement.compile()

By default, the statement is compiled using a basic ‘named’ implementation that is compatible with SQL databases such as SQLite and Oracle. If you need to specify a dialect such as PostgreSQL, you can do

from sqlalchemy.dialects import postgresql
query = statement.compile(dialect=postgresql.dialect())

Or if you want to explicitly specify the dialect as SQLite, you can change the paramstyle from ‘qmark’ to ‘named’.

from sqlalchemy.dialects import sqlite
query = statement.compile(dialect=sqlite.dialect(paramstyle="named"))

From the query object, we can extract the query string and query parameters

query_str = str(query)
query_params = query.params

and finally execute the query.

conn.execute( query_str, query_params )

回答 8

您可以使用ConnectionEvents系列的事件:after_cursor_executebefore_cursor_execute

@zzzeek提供的sqlalchemy UsageRecipes中,您可以找到以下示例:

Profiling

...
@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement,
                        parameters, context, executemany):
    conn.info.setdefault('query_start_time', []).append(time.time())
    logger.debug("Start Query: %s" % statement % parameters)
...

在这里您可以访问您的对帐单

You can use events from ConnectionEvents family: after_cursor_execute or before_cursor_execute.

In sqlalchemy UsageRecipes by @zzzeek you can find this example:

Profiling

...
@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement,
                        parameters, context, executemany):
    conn.info.setdefault('query_start_time', []).append(time.time())
    logger.debug("Start Query: %s" % statement % parameters)
...

Here you can get access to your statement


回答 9

因此,将这些不同答案的很多点放在一起,我得出了我需要的东西:一组简单的代码可以插入,偶尔但可靠地(即处理所有数据类型)获取发送给我的准确的,已编译的SQL通过查询查询本身的Postgres后端:

from sqlalchemy.dialects import postgresql

query = [ .... some ORM query .... ]

compiled_query = query.statement.compile(
    dialect=postgresql.dialect()
)
mogrified_query = session.connection().connection.cursor().mogrify(
    str(compiled_query),
    compiled_query.params
)

print("compiled SQL = {s}".format(mogrified_query.decode())

So, putting together a lot of little bits of these different answers, I came up with what I needed: a simple set of code to drop in and occasionally but reliably (i.e. handles all data types) grab the exact, compiled SQL sent to my Postgres backend by just interrogating the query itself:

from sqlalchemy.dialects import postgresql

query = [ .... some ORM query .... ]

compiled_query = query.statement.compile(
    dialect=postgresql.dialect(),
    compile_kwargs={"literal_binds": True}
)
mogrified_query = session.connection().connection.cursor().mogrify(
    str(compiled_query),
    compiled_query.params
)

print("compiled SQL = {s}".format(mogrified_query.decode())

回答 10

我认为.statement可能会解决问题:http ://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query

>>> local_session.query(sqlalchemy_declarative.SomeTable.text).statement
<sqlalchemy.sql.annotation.AnnotatedSelect at 0x6c75a20; AnnotatedSelectobject>
>>> x=local_session.query(sqlalchemy_declarative.SomeTable.text).statement
>>> print(x)
SELECT sometable.text 
FROM sometable

I think .statement would possibly do the trick: http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query

>>> local_session.query(sqlalchemy_declarative.SomeTable.text).statement
<sqlalchemy.sql.annotation.AnnotatedSelect at 0x6c75a20; AnnotatedSelectobject>
>>> x=local_session.query(sqlalchemy_declarative.SomeTable.text).statement
>>> print(x)
SELECT sometable.text 
FROM sometable

如何在Mac OS X上安装MySQLdb(MySQL的Python数据访问库)?

问题:如何在Mac OS X上安装MySQLdb(MySQL的Python数据访问库)?

我是Python的新手,但是我只花了一天的时间来研究如何使MySQLdb正常工作,而根据Google的说法,Universe包含了许多有关PITA是什么的参考,并且似乎有大量的指南。过时的。鉴于此站点旨在解决此类问题,并且我知道将来需要该解决方案的参考,因此我将提出问题,提供答案并查看还有哪些问题表面。

所以问题是如何使MySQLdb在Mac OS X上运行?

I’m a Python newbie, but I’ve just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I’m going to need a reference to the solution in future, I’m going to ask the question, provide my answer and see what else floats to the surface.

So the question is how to get MySQLdb working on Mac OS X?


回答 0

使用Python3的用户的更新: 您可以简单地conda install mysqlclient用来安装使用MySQLdb所需的库,因为它目前存在。以下SO问题是一个有用的线索:Python 3 ImportError:没有名为’ConfigParser’的模块。安装mysqlclient将安装mysqlclient,mysql-connector和llvmdev(至少在我的机器上安装了这3个库)。

这是我关于这个问题的漫漫经历的故事。如果您对问题有更好的经验,不妨看一下它的编辑或概括…应用一下这种SO魔术。

注意:下一段中的注释适用于Snow Leopard,但不适用于Lion,后者似乎需要64位MySQL

首先,MySQLdb的作者(还是?)在这里说,最有害的问题之一是OS X附带了32位版本的Python,但是大多数普通人(包括我自己)都可能安装了64位版本。 MySQL。不好动…删除64位版本,如果你已经安装了它(这个繁琐的任务指令适用于SO 这里),然后下载并(包安装32位版本在这里

关于如何构建和安装MySQLdb库,有许多分步说明。它们通常有细微的差异。 对我来说似乎最受欢迎,并提供了可行的解决方案。我在下面进行了一些修改,复制了它

步骤0: 开始之前,我假设您在Mac上安装了MySQL,Python和GCC

步骤1:从SourceForge 下载最新的MySQL for Python适配器

步骤2:解 压缩下载的软件包:

tar xzvf MySQL-python-1.2.2.tar.gz

步骤3: 在文件夹内,清洁包装:

sudo python setup.py clean

额外步骤,(来自此评论

步骤3b: 删除MySQL-python-1.2.2 / build / *目录下的所有内容-不要相信“ python setup.py clean”为您完成此操作

步骤3c: 删除Users / $ USER / .python-eggs下的鸡蛋

步骤4: 最初需要编辑_mysql.c,但现在不再需要。MySQLdb社区似乎已经修复了此错误。

步骤5: 在lib下创建一个符号链接,以指向一个名为mysql的子目录。这是编译期间要查找的位置。

sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql

步骤6: 编辑setup_posix.py并更改以下内容

mysql_config.path =“ mysql_config”

mysql_config.path =“ / usr / local / mysql / bin / mysql_config”

步骤7: 在同一个目录中,重建您的软件包(忽略软件包附带的警告)

sudo python setup.py build

步骤8: 安装软件包,您已完成。

sudo python setup.py install

第9步: 测试它是否正常工作。如果可以导入MySQLdb,则可以使用。

python

>>> import MySQLdb

步骤10: 如果在尝试导入时收到错误消息,提示Library not loaded: libmysqlclient.18.dylib以以下结尾:Reason: image not found您需要创建一个附加的符号链接,即:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

然后,您应该能够import MySQLdb没有任何错误。

最后一个麻烦是,如果您从构建目录启动Python,则会出现此错误:

/Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.py:3:用户警告:模块_mysql已从/Library/Python/2.5/中导入site-packages / MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg / _mysql.pyc,但XXXX / MySQL-python-1.2.3c1已添加到sys.path

这对Google来说很容易,但是要为您省去麻烦,您将最终在这里(或者可能不是……不是特别适合未来的URL),并发现您需要cd ..脱离构建目录,并且错误应该消失。

正如我在顶部写的那样,我很乐意看到这个答案具有普遍性,因为对于这个可怕的问题还有很多其他的具体经验。编辑掉,或者提供自己的更好的答案。

Update for those using Python3: You can simply use conda install mysqlclient to install the libraries required to use MySQLdb as it currently exists. The following SO question was a helpful clue: Python 3 ImportError: No module named ‘ConfigParser’ . Installing mysqlclient will install mysqlclient, mysql-connector, and llvmdev (at least, it installed these 3 libraries on my machine).

Here is the tale of my rambling experience with this problem. Would love to see it edited or generalised if you have better experience of the issue… apply a bit of that SO magic.

Note: Comments in next paragraph applied to Snow Leopard, but not to Lion, which appears to require 64-bit MySQL

First off, the author (still?) of MySQLdb says here that one of the most pernicious problems is that OS X comes installed with a 32 bit version of Python, but most average joes (myself included) probably jump to install the 64 bit version of MySQL. Bad move… remove the 64 bit version if you have installed it (instructions on this fiddly task are available on SO here), then download and install the 32 bit version (package here)

There are numerous step-by-steps on how to build and install the MySQLdb libraries. They often have subtle differences. This seemed the most popular to me, and provided the working solution. I’ve reproduced it with a couple of edits below

Step 0: Before I start, I assume that you have MySQL, Python, and GCC installed on the mac.

Step 1: Download the latest MySQL for Python adapter from SourceForge.

Step 2: Extract your downloaded package:

tar xzvf MySQL-python-1.2.2.tar.gz

Step 3: Inside the folder, clean the package:

sudo python setup.py clean

COUPLE OF EXTRA STEPS, (from this comment)

Step 3b: Remove everything under your MySQL-python-1.2.2/build/* directory — don’t trust the “python setup.py clean” to do it for you

Step 3c: Remove the egg under Users/$USER/.python-eggs

Step 4: Originally required editing _mysql.c, but is now NO LONGER NECESSARY. MySQLdb community seem to have fixed this bug now.

Step 5: Create a symbolic link under lib to point to a sub-directory called mysql. This is where it looks for during compilation.

sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql

Step 6: Edit the setup_posix.py and change the following

mysql_config.path = “mysql_config”

to

mysql_config.path = “/usr/local/mysql/bin/mysql_config”

Step 7: In the same directory, rebuild your package (ignore the warnings that comes with it)

sudo python setup.py build

Step 8: Install the package and you are done.

sudo python setup.py install

Step 9: Test if it’s working. It works if you can import MySQLdb.

python

>>> import MySQLdb

Step 10: If upon trying to import you receive an error complaining that Library not loaded: libmysqlclient.18.dylib ending with: Reason: image not found you need to create one additional symlink which is:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

You should then be able to import MySQLdb without any errors.

One final hiccup though is that if you start Python from the build directory you will get this error:

/Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.pyc, but XXXX/MySQL-python-1.2.3c1 is being added to sys.path

This is pretty easy to Google, but to save you the trouble you will end up here (or maybe not… not a particularly future-proof URL) and figure out that you need to cd .. out of build directory and the error should disappear.

As I wrote at the top, I’d love to see this answer generalised, as there are numerous other specific experiences of this horrible problem out there. Edit away, or provide your own, better answer.


回答 1

适用于Mac OS X 10.8(Mountain Lion),10.9(Mavericks),10.10(Yosemite)和10.11(El Capitan)的快速简便的方法:

我假设您已经安装了XCode,其命令行工具,Python和MySQL。

  1. 安装PIP:

    sudo easy_install pip
  2. 编辑〜/ .profile :(在Mac OS X 10.10中可能不需要)

    nano ~/.profile

    复制并粘贴以下两行

    export PATH=/usr/local/mysql/bin:$PATH
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/

    保存并退出。后记执行以下命令:

    source  ~/.profile
  3. 安装MySQLdb

    sudo pip install MySQL-python

    要测试一切是否正常,请尝试

    python -c "import MySQLdb"

对我来说,它就像是一种魅力。希望对您有所帮助。

如果遇到有关缺少库的错误:库未加载:libmysqlclient.18.dylib,则必须将其符号链接为/usr/lib

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib 

A quick and easy way for Mac OS X 10.8 (Mountain Lion), 10.9 (Mavericks), 10.10 (Yosemite), and 10.11 (El Capitan):

I assume you have XCode, its command line tools, Python, and MySQL installed.

  1. Install PIP:

    sudo easy_install pip
    
  2. Edit ~/.profile: (Might not be necessary in Mac OS X 10.10)

    nano ~/.profile
    

    Copy and paste the following two line

    export PATH=/usr/local/mysql/bin:$PATH
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
    

    Save and exit. Afterwords execute the following command:

    source  ~/.profile
    
  3. Install MySQLdb

    sudo pip install MySQL-python
    

    To test if everything works fine just try

    python -c "import MySQLdb"
    

It worked like a charm for me. I hope it helps.

If you encounter an error regarding a missing library: Library not loaded: libmysqlclient.18.dylib then you have to symlink it to /usr/lib like so:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib 

回答 2

通过Macports安装mysql和python 搬运工完成了所有困难的工作。

sudo port install py26-mysql 
sudo port install mysql5-server

应该安装您需要的东西。(请参阅堆栈溢出以获取有关mysql服务器的注释

如果只需要连接到mysql而不运行服务器,那么第一行就足够了。

Macports现在(2013年初)将为操作系统的常见组合和可执行体系结构提供二进制下载,而对于其他操作系统(如果需要),它将从源代码构建。

通常,当有复杂的库等需要安装时,macports(或fink)会提供帮助。

仅使用Python的代码,如果可以通过setuptools等设置简单的C依赖关系,但是如果将两者混合使用,它就会变得复杂起来。

Install mysql and python via Macports The porters have done all the difficult work.

sudo port install py26-mysql 
sudo port install mysql5-server

should install what you need. (see Stack overflow for comments re mysql server)

If you only need to connect to mysql and not run a server then the first line is sufficient.

Macports now (early 2013) will provide binary downloads for common combinations of OS a executable architecture, for others (and if you request it) it will build from source.

In general macports (or fink) help when there are complex libraries etc that need to be installed.

Python only code and if simple C dependencies can be set up via setuptools etc, but it begins to get complex if you mix the two.


回答 3

安装点子:

sudo easy_install pip

安装brew:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

安装mysql:

brew install mysql

安装MySQLdb

sudo pip install MySQL-python

如果您遇到编译问题,请尝试编辑〜/ .profile文件,如此处的答案之一所示。

Install pip:

sudo easy_install pip

Install brew:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Install mysql:

brew install mysql

Install MySQLdb

sudo pip install MySQL-python

If you have compilation problems, try editing the ~/.profile file like in one of the answers here.


回答 4

在完成第9步时收到错误消息后,我还必须完成另一个步骤:

ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

参考:谢谢!http://ageekstory.blogspot.com/2011_04_01_archive.html

Here’s another step I had to go through, after receiving an error on completing Step 9:

ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Reference: Thanks! http://ageekstory.blogspot.com/2011_04_01_archive.html


回答 5

在Mac安装MySQL-python所述

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

然后测试一下:

python -c "import MySQLdb"

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

回答 6

刚得到一个新的Lion盒之后,又遇到了这个问题(再次!)。

我发现的最佳解决方案(仍然不是100%最佳,但可以工作):

可以通过从Apple下载XCode / Dev工具获得它-这是一个很大的下载-

…但是我推荐这个github,它具有您所需要的(并且没有XCode):https : //github.com/kennethreitz/osx-gcc-installer

我下载了他们为狮子预装的PKG,https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg

  • 确保您已下载64位版本的MYSQL社区。(DMG安装是一条简单的路线)http://dev.mysql.com/downloads/mysql/

  • 设置路径如下:

    导出PATH = $ PATH:/ usr / local / mysql-XXXX

    导出DYLD_LIBRARY_PATH = / usr / local / mysql / lib /

    出口ARCHFLAGS =’-arch x86_64′

注意:

在上面的mysql-XXXX中为1,XXX是您下载的特定版本。(也许/ usr / local / mysql /也可以工作,因为这很可能是相同的别名,但是我不会假装知道您的设置)

2我已经看到它建议将ARCHFLAGS设置为’-arch i386 -arch x86_64’,但是仅指定x86_64似乎对我来说更好。(我可以想到一些原因,但是它们并不严格相关)。

  • 安装野兽!

    easy_install MySQL-python

  • 最后一步:

永久添加DYLD_LIBRARY_PATH!

您可以将其添加到您的bash_profile或类似文件中。这是我所缺少的步骤,没有它,我的系统将继续坚持各种错误来查找_mysql.so等。

导出DYLD_LIBRARY_PATH = / usr / local / mysql / lib /

@ richard-boardman,刚注意到您的软链接解决方案,实际上可能是在执行我的PATH解决方案所做的相同工作……民间,无论哪种方法最适合您。

最佳参考:http : //activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/

Just had this problem (again!) after getting a new Lion box.

Best solution I’ve found (still not 100% optimal, but working):

you can get it by downloading XCode/Dev Tools from Apple – this is a big download –

… but instead I recommend this github which has what you need (and does not have XCode): https://github.com/kennethreitz/osx-gcc-installer

I downloaded their prebuilt PKG for lion, https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg

  • make sure you have downloaded a 64-BIT version of MYSQL Community. (The DMG install is an easy route) http://dev.mysql.com/downloads/mysql/

  • Set paths as follows:

    export PATH=$PATH:/usr/local/mysql-XXXX

    export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

    export ARCHFLAGS=’-arch x86_64′

NOTE THAT:

1 in mysql-XXXX above, XXX is the specific version you downloaded. (Probably /usr/local/mysql/ would also work since this is most likely an alias to the same, but I won’t pretend to know your setup)

2 I have seen it suggested that ARCHFLAGS be set to ‘-arch i386 -arch x86_64’ but specifying only x86_64 seemed to work better for me. (I can think of some reasons for this but they are not strictly relevant).

  • Install the beast!

    easy_install MySQL-python

  • LAST STEP:

Permanently add the DYLD_LIBRARY_PATH!

You can add it to your bash_profile or similar. This was the missing step for me, without which my system continued to insist on various errors finding _mysql.so and so on.

export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

@richard-boardman, just noticed your soft link solution, which may in effect be doing the same thing my PATH solution does…folks, whatever works best for you.

Best reference: http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/


回答 7

您可以尝试使用pure-python pymysql

sudo easy_install pymysql

(或者使用pip是否已安装。)然后,import MySQLdb在代码中添加以下代码:

try:
    import pymysql
    pymysql.install_as_MySQLdb()
except ImportError:
    pass

You could try using the pure-python pymysql:

sudo easy_install pymysql

(Or use pip if you have it installed.) Then, add this before you import MySQLdb in your code:

try:
    import pymysql
    pymysql.install_as_MySQLdb()
except ImportError:
    pass

回答 8

或简单尝试:

> sudo easy_install MySQL-python

如果出现如下错误:

EnvironmentError:找不到mysql_config

,然后运行

> export PATH=$PATH:/usr/local/mysql/bin

Or simple try:

> sudo easy_install MySQL-python

If it gives a error like below:

EnvironmentError: mysql_config not found

, then just run this

> export PATH=$PATH:/usr/local/mysql/bin

回答 9

如果您使用的是64位MySQL,则在构建mysql-python库时使用ARCHFLAGS指定您的cpu体系结构将达到目的:

ARCHFLAGS='-arch x86_64' python setup.py build
ARCHFLAGS='-arch x86_64' python setup.py install

If you are using 64 bit MySQL, using ARCHFLAGS to specify your cpu architecture while building mysql-python libraries would do the trick:

ARCHFLAGS='-arch x86_64' python setup.py build
ARCHFLAGS='-arch x86_64' python setup.py install

回答 10

export PATH=$PATH:/usr/local/mysql/bin/

应该会为您解决该问题,因为系统无法找到mysql_config文件。

export PATH=$PATH:/usr/local/mysql/bin/

should fix the issue for you as the system is not able to find the mysql_config file.


回答 11

在macos Sierra上,这对我有用,其中Python由anaconda管理:

anaconda search -t conda mysql-python

anaconda show CEFCA/mysql-python

conda install --channel https://conda.anaconda.org/CEFCA mysql-python

与SQLAlchemy一起使用:

Python 2.7.13 | Continuum Analytics,Inc. | (默认值,2016年12月20日,23:05:08)darwin上的[GCC 4.2.1兼容Apple LLVM 6.0(clang-600.0.57)]有关更多信息,请键入“ help”,“ copyright”,“ credits”或“ license”信息。Anaconda由Continuum Analytics带给您。请检出:http : //continuum.io/thankshttps://anaconda.org

>>>从sqlalchemy导入*

>>> dbengine = create_engine(’mysql:// ….’)

On macos Sierra this work for me, where python is managed by anaconda:

anaconda search -t conda mysql-python

anaconda show CEFCA/mysql-python

conda install --channel https://conda.anaconda.org/CEFCA mysql-python

The to use with SQLAlchemy:

Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type “help”, “copyright”, “credits” or “license” for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org

>>> from sqlalchemy import *

>>>dbengine = create_engine(‘mysql://….’)


回答 12

这个答案是大约在2019年11月的更新。没有一个流行的pip安装程序可以在MacOS 10.13(以及其他版本)上为您提供有效的安装程序。这是使工作正常的一种简单方法:

brew install mysql
pip install mysqlclient

如果需要安装brew的帮助,请访问以下站点:https : //brew.sh/

This answer is an update, circa November 2019. None of the popular pip installs will give you a working setup on MacOS 10.13 (and likely other versions as well). Here is a simple way that I got things working:

brew install mysql
pip install mysqlclient

If you need help installing brew, see this site: https://brew.sh/


回答 13

我遇到了这个问题,发现mysqlclient需要知道在哪里可以找到openssl,而OSX默认将其隐藏。

使用找到“ openssl” brew info openssl,然后将opensslbin 的路径添加到PATH:

export PATH="/usr/local/opt/openssl/bin:$PATH"

我建议将其添加到您的.zshrc或.bashrc中,这样以后就不必担心了。然后,导出该变量(可能需要关闭并重新打开bash会话),再添加两个env变量:

# in terminal
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

然后,最后运行:

pipenv install mysqlclient

它应该安装得很好。

来源:https//medium.com/@shandou/pipenv-install-mysqlclient-on-macosx-7c253b0112f2

I ran into this issue and found that mysqlclient needs to know where to find openssl, and OSX hides this by default.

Locate openssl with brew info openssl, and then add the path to your openssl bin to your PATH:

export PATH="/usr/local/opt/openssl/bin:$PATH"

I recommend adding that to your .zshrc or .bashrc so you don’t need to worry about it in the future. Then, with that variable exported (which may meed closing and re-opening your bash session), add two more env variables:

# in terminal
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

Then, finally, run:

pipenv install mysqlclient

and it should install just fine.

Source: https://medium.com/@shandou/pipenv-install-mysqlclient-on-macosx-7c253b0112f2


在Django中保存Unicode字符串时,MySQL“字符串值不正确”错误

问题:在Django中保存Unicode字符串时,MySQL“字符串值不正确”错误

尝试将first_name,last_name保存到Django的auth_user模型时,出现奇怪的错误消息。

失败的例子

user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'Slatkevičius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_name' at row 104

user.first_name = u'Валерий'
user.last_name = u'Богданов'
user.save()
>>> Incorrect string value: '\xD0\x92\xD0\xB0\xD0\xBB...' for column 'first_name' at row 104

user.first_name = u'Krzysztof'
user.last_name = u'Szukiełojć'
user.save()
>>> Incorrect string value: '\xC5\x82oj\xC4\x87' for column 'last_name' at row 104

成功的例子

user.first_name = u'Marcin'
user.last_name = u'Król'
user.save()
>>> SUCCEED

MySQL设置

mysql> show variables like 'char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       | 
| character_set_connection | utf8                       | 
| character_set_database   | utf8                       | 
| character_set_filesystem | binary                     | 
| character_set_results    | utf8                       | 
| character_set_server     | utf8                       | 
| character_set_system     | utf8                       | 
| character_sets_dir       | /usr/share/mysql/charsets/ | 
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

表字符集和排序规则

表auth_user具有utf-8字符集,并带有utf8_general_ci排序规则。

UPDATE命令的结果

使用UPDATE命令将上述值更新到auth_user表时,它没有引发任何错误。

mysql> update auth_user set last_name='Slatkevičiusa' where id=1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select last_name from auth_user where id=100;
+---------------+
| last_name     |
+---------------+
| Slatkevi?iusa | 
+---------------+
1 row in set (0.00 sec)

PostgreSQL的

当我在Django中切换数据库后端时,上面列出的失败值可以更新到PostgreSQL表中。真奇怪。

mysql> SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset  | Description                 | Default collation   | Maxlen |
+----------+-----------------------------+---------------------+--------+
...
| utf8     | UTF-8 Unicode               | utf8_general_ci     |      3 | 
...

但是从http://www.postgresql.org/docs/8.1/interactive/multibyte.html,我发现了以下内容:

Name Bytes/Char
UTF8 1-4

这是否意味着unicode char在PostgreSQL中的maxlen为4个字节,而在MySQL中为3个字节,这导致了上述错误?

I got strange error message when tried to save first_name, last_name to Django’s auth_user model.

Failed examples

user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'Slatkevičius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_name' at row 104

user.first_name = u'Валерий'
user.last_name = u'Богданов'
user.save()
>>> Incorrect string value: '\xD0\x92\xD0\xB0\xD0\xBB...' for column 'first_name' at row 104

user.first_name = u'Krzysztof'
user.last_name = u'Szukiełojć'
user.save()
>>> Incorrect string value: '\xC5\x82oj\xC4\x87' for column 'last_name' at row 104

Succeed examples

user.first_name = u'Marcin'
user.last_name = u'Król'
user.save()
>>> SUCCEED

MySQL settings

mysql> show variables like 'char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       | 
| character_set_connection | utf8                       | 
| character_set_database   | utf8                       | 
| character_set_filesystem | binary                     | 
| character_set_results    | utf8                       | 
| character_set_server     | utf8                       | 
| character_set_system     | utf8                       | 
| character_sets_dir       | /usr/share/mysql/charsets/ | 
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

Table charset and collation

Table auth_user has utf-8 charset with utf8_general_ci collation.

Results of UPDATE command

It didn’t raise any error when updating above values to auth_user table by using UPDATE command.

mysql> update auth_user set last_name='Slatkevičiusa' where id=1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select last_name from auth_user where id=100;
+---------------+
| last_name     |
+---------------+
| Slatkevi?iusa | 
+---------------+
1 row in set (0.00 sec)

PostgreSQL

The failed values listed above can be updated into PostgreSQL table when I switched the database backend in Django. It’s strange.

mysql> SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset  | Description                 | Default collation   | Maxlen |
+----------+-----------------------------+---------------------+--------+
...
| utf8     | UTF-8 Unicode               | utf8_general_ci     |      3 | 
...

But from http://www.postgresql.org/docs/8.1/interactive/multibyte.html, I found the following:

Name Bytes/Char
UTF8 1-4

Is it means unicode char has maxlen of 4 bytes in PostgreSQL but 3 bytes in MySQL which caused above error?


回答 0

这些答案都没有为我解决问题。根本原因是:

您不能在MySQL中使用utf-8字符集存储4字节字符。

MySQL的utf-8字符限制3个字节(是的,这很奇怪,Django开发人员在这里总结得很好

要解决此问题,您需要:

  1. 更改您的MySQL数据库,表和列以使用utf8mb4字符集(仅从MySQL 5.5起可用)
  2. 在Django设置文件中指定字符集,如下所示:

settings.py

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        ...
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

注意:重新创建数据库时,您可能会遇到“ 指定密钥太长 ”的问题。

最可能的原因是a CharField,它的max_length为255,上面有某种索引(例如,唯一)。由于utf8mb4比utf-8使用的空间多33%,因此您需要将这些字段缩小33%。

在这种情况下,请将max_length从255更改为191。

或者,您可以编辑MySQL配置以消除此限制, 但是要注意一些django hackery

更新:我只是再次遇到这个问题,最终因为无法将我的字符数减少到191个而切换到PostgreSQLVARCHAR

None of these answers solved the problem for me. The root cause being:

You cannot store 4-byte characters in MySQL with the utf-8 character set.

MySQL has a 3 byte limit on utf-8 characters (yes, it’s wack, nicely summed up by a Django developer here)

To solve this you need to:

  1. Change your MySQL database, table and columns to use the utf8mb4 character set (only available from MySQL 5.5 onwards)
  2. Specify the charset in your Django settings file as below:

settings.py

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        ...
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

Note: When recreating your database you may run into the ‘Specified key was too long‘ issue.

The most likely cause is a CharField which has a max_length of 255 and some kind of index on it (e.g. unique). Because utf8mb4 uses 33% more space than utf-8 you’ll need to make these fields 33% smaller.

In this case, change the max_length from 255 to 191.

Alternatively you can edit your MySQL configuration to remove this restriction but not without some django hackery

UPDATE: I just ran into this issue again and ended up switching to PostgreSQL because I was unable to reduce my VARCHAR to 191 characters.


回答 1

我遇到了同样的问题,并通过更改列的字符集解决了它。即使您的数据库具有默认字符集,utf-8我也认为数据库列在MySQL中可能具有不同的字符集。这是我使用的SQL查询:

    ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
    CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of utf-8 I think it’s possible for database columns to have a different character set in MySQL. Here’s the SQL QUERY I used:

    ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
    CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

回答 2

如果您有此问题,请使用以下python脚本自动更改mysql数据库的所有列。

#! /usr/bin/env python
import MySQLdb

host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()

cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
  sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
  cursor.execute(sql)
db.close()

If you have this problem here’s a python script to change all the columns of your mysql database automatically.

#! /usr/bin/env python
import MySQLdb

host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()

cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
  sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
  cursor.execute(sql)
db.close()

回答 3

如果这是一个新项目,则只需删除数据库,然后使用适当的字符集创建一个新项目:

CREATE DATABASE <dbname> CHARACTER SET utf8;

If it’s a new project, I’d just drop the database, and create a new one with a proper charset:

CREATE DATABASE <dbname> CHARACTER SET utf8;

回答 4

我只是想出一种避免上述错误的方法。

保存到数据库

user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevičius'.encode('unicode_escape')
user.save()
>>> SUCCEED

print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevičius

这是将这样的字符串保存到MySQL表中并在渲染为模板进行显示之前对其进行解码的唯一方法吗?

I just figured out one method to avoid above errors.

Save to database

user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevičius'.encode('unicode_escape')
user.save()
>>> SUCCEED

print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevičius

Is this the only method to save strings like that into a MySQL table and decode it before rendering to templates for display?


回答 5

您可以将文本字段的排序规则更改为UTF8_general_ci,此问题将得到解决。

注意,这不能在Django中完成。

You can change the collation of your text field to UTF8_general_ci and the problem will be solved.

Notice, this cannot be done in Django.


回答 6

您不是要保存unicode字符串,而是要以UTF-8编码保存字节字符串。使它们成为实际的unicode字符串文字:

user.last_name = u'Slatkevičius'

或(当您没有字符串文字时)使用utf-8编码对其进行解码:

user.last_name = lastname.decode('utf-8')

You aren’t trying to save unicode strings, you’re trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:

user.last_name = u'Slatkevičius'

or (when you don’t have string literals) decode them using the utf-8 encoding:

user.last_name = lastname.decode('utf-8')

回答 7

只需更改您的表,无需任何操作。只需在数据库上运行此查询。 更改表table_name转换为字符集utf8

它一定会工作。

Simply alter your table, no need to any thing. just run this query on database. ALTER TABLE table_nameCONVERT TO CHARACTER SET utf8

it will definately work.


回答 8

改进@madprops答案-解决方案作为Django管理命令:

import MySQLdb
from django.conf import settings

from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def handle(self, *args, **options):
        host = settings.DATABASES['default']['HOST']
        password = settings.DATABASES['default']['PASSWORD']
        user = settings.DATABASES['default']['USER']
        dbname = settings.DATABASES['default']['NAME']

        db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
        cursor = db.cursor()

        cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

        sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
        cursor.execute(sql)

        results = cursor.fetchall()
        for row in results:
            print(f'Changing table "{row[0]}"...')
            sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
            cursor.execute(sql)
        db.close()

希望这可以帮助我以外的任何人:)

Improvement to @madprops answer – solution as a django management command:

import MySQLdb
from django.conf import settings

from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def handle(self, *args, **options):
        host = settings.DATABASES['default']['HOST']
        password = settings.DATABASES['default']['PASSWORD']
        user = settings.DATABASES['default']['USER']
        dbname = settings.DATABASES['default']['NAME']

        db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
        cursor = db.cursor()

        cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

        sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
        cursor.execute(sql)

        results = cursor.fetchall()
        for row in results:
            print(f'Changing table "{row[0]}"...')
            sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
            cursor.execute(sql)
        db.close()

Hope this helps anybody but me :)


如何在Windows上的Python 3中连接到MySQL?

问题:如何在Windows上的Python 3中连接到MySQL?

我在Windows上使用ActiveState Python 3,并想连接到我的MySQL数据库。我听说这mysqldb是要使用的模块。我找不到mysqldbPython 3。

有二进制文件存在的存储库mysqldb吗?如何在Windows的Python 3中连接到MySQL?

I am using ActiveState Python 3 on Windows and wanted to connect to my MySQL database. I heard that mysqldb was the module to use. I can’t find mysqldb for Python 3.

Is there a repository available where the binaries exist for mysqldb? How can I connect to MySQL in Python 3 on Windows?


回答 0

当前有一些将python 3与mysql结合使用的选项:

https://pypi.python.org/pypi/mysql-connector-python

  • 由Oracle官方支持
  • 纯Python
  • 有点慢
  • 与MySQLdb不兼容

https://pypi.python.org/pypi/pymysql

  • 纯Python
  • 比mysql-connector快
  • MySQLdb调用后几乎与完全兼容pymysql.install_as_MySQLdb()

https://pypi.python.org/pypi/cymysql

  • pymysql的fork与可选的C加速

https://pypi.python.org/pypi/mysqlclient

  • Django推荐的库。
  • 原始MySQLdb的友好分支,希望有一天能合并
  • 最快的实现,因为它基于C。
  • 与MySQLdb最兼容,因为它是一个fork
  • Debian和Ubuntu使用它来提供python-mysqldbpython3-mysqldb软件包。

此处的基准测试:https//github.com/methane/mysql-driver-benchmarks

There are currently a few options for using Python 3 with mysql:

https://pypi.python.org/pypi/mysql-connector-python

  • Officially supported by Oracle
  • Pure python
  • A little slow
  • Not compatible with MySQLdb

https://pypi.python.org/pypi/pymysql

  • Pure python
  • Faster than mysql-connector
  • Almost completely compatible with MySQLdb, after calling pymysql.install_as_MySQLdb()

https://pypi.python.org/pypi/cymysql

  • fork of pymysql with optional C speedups

https://pypi.python.org/pypi/mysqlclient

  • Django’s recommended library.
  • Friendly fork of the original MySQLdb, hopes to merge back some day
  • The fastest implementation, as it is C based.
  • The most compatible with MySQLdb, as it is a fork
  • Debian and Ubuntu use it to provide both python-mysqldb andpython3-mysqldb packages.

benchmarks here: https://github.com/methane/mysql-driver-benchmarks


回答 1

您可能应该使用pymysql-纯Python MySQL客户端
它与Python 3.x兼容,并且没有任何依赖关系。

这个纯Python MySQL客户端通过二进制客户端/服务器协议直接与服务器通信,从而为MySQL数据库提供DB-API。

例:

import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
    print(r)
cur.close()
conn.close()

You should probably use pymysql – Pure Python MySQL client instead.
It works with Python 3.x, and doesn’t have any dependencies.

This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.

Example:

import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
    print(r)
cur.close()
conn.close()

回答 2

我也尝试使用pymysql(在Win7 x64计算机上,Python 3.3),但运气不佳。我下载了.tar.gz,解压缩并运行“ setup.py install”,一切似乎都很好。直到我尝试连接到数据库并得到“ KeyError [56]”。我找不到任何地方记录的错误。

因此,我放弃了pymysql,而选择了Oracle MySQL连接器

它作为安装程序包提供,开箱即用。而且似乎也有据可查。

I also tried using pymysql (on my Win7 x64 machine, Python 3.3), without too much luck. I downloaded the .tar.gz, extract, ran “setup.py install”, and everything seemed fine. Until I tried connecting to a database, and got “KeyError [56]”. An error which I was unable to find documented anywhere.

So I gave up on pymysql, and I settled on the Oracle MySQL connector.

It comes as a setup package, and works out of the box. And it also seems decently documented.


回答 3

如果要先使用MySQLdb,则必须在Windows上键入cmd,在PC上安装pymysql

    pip install pymysql

然后在python shell中键入

    import pymysql
    pymysql.install_as_MySQLdb()
    import MySQLdb
    db = MySQLdb.connect("localhost" , "root" , "password")

这将建立连接。

if you want to use MySQLdb first you have to install pymysql on your pc by typing in cmd of windows

    pip install pymysql

then in python shell, type

    import pymysql
    pymysql.install_as_MySQLdb()
    import MySQLdb
    db = MySQLdb.connect("localhost" , "root" , "password")

this will establish the connection.


回答 4

未经测试,但在以下位置有一些可用的二进制文件:

非官方Windows二进制文件

Untested, but there are some binaries available at:

Unofficial Windows Binaries


回答 5

摘要

Mysqlclient是最佳选择(IMHO),因为它可以与Python 3+完美 协作,遵循预期的约定(与mysql连接器不同),使用对象名称mysqldb可以方便地移植现有软件,并且由Django用于python 3构建

mysqldb的二进制文件存在的地方有可用的存储库吗?

是。 mysqlclient允许您使用mysqldb函数。虽然,请记住,这不是 mysqldb 的直接端口,而是mysqlclient的构建

如何在Windows上的Python 3中连接到MySQL?

pip安装mysqlclient

#!/Python36/python
#Please change above path to suit your platform.  Am running it on Windows
import MySQLdb
db = MySQLdb.connect(user="my-username",passwd="my-password",host="localhost",db="my-databasename")
cursor = db.cursor()
cursor.execute("SELECT * from my-table-name")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

我找不到适用于Python 3的mysqldb。

mysqldb尚未移植

Summary

Mysqlclient is the best alternative(IMHO) because it works flawlessly with Python 3+, follows expected conventions (unlike mysql connector), uses the object name mysqldb which enables convenient porting of existing software and is used by Django for Python 3 builds

Is there a repository available where the binaries exist for mysqldb?

Yes. mysqlclient allows you to use mysqldb functions. Though, remember this is not a direct port by mysqldb, but a build by mysqlclient

How can I connect to MySQL in Python 3 on Windows?

pip install mysqlclient

Example

#!/Python36/python
#Please change above path to suit your platform.  Am running it on Windows
import MySQLdb
db = MySQLdb.connect(user="my-username",passwd="my-password",host="localhost",db="my-databasename")
cursor = db.cursor()
cursor.execute("SELECT * from my-table-name")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

I can’t find mysqldb for Python 3.

mysqldb has not been ported yet


回答 6

PyMySQL也提供类似MySQLDb的界面。您可以尝试进行初始化:

import pymysql
pymysql.install_as_MySQLdb()

github上还有一个用于python3的mysql-python端口。

https://github.com/davispuh/MySQL-for-Python-3

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3


回答 7

Oracle / MySQL提供了一个官方的纯Python DBAPI驱动程序:http ://dev.mysql.com/downloads/connector/python/

我在Python 3.3中使用了它,并发现它运行良好。还可以与SQLAlchemy一起使用。

另请参阅以下问题:登上Python 3火车是否还为时过早?

Oracle/MySQL provides an official, pure Python DBAPI driver: http://dev.mysql.com/downloads/connector/python/

I have used it with Python 3.3 and found it to work great. Also works with SQLAlchemy.

See also this question: Is it still too early to hop aboard the Python 3 train?


回答 8

在我的Mac OS X上,我尝试这样做:

之后,输入python3解释器并输入:

  1. 导入pymysql。如果没有错误,则表示安装正常。为了验证,编写一个脚本以这种形式连接到mysql:

  2. #一个用于MySQL连接的简单脚本import pymysql db = pymysql.connect(host =“ localhost”,user =“ root”,passwd =“* “,db =” biblioteca“)#当然,这是我的数据库的信息#关闭连接db.close()*

给它起一个名字(例如“ con.py”)并将其保存在桌面上。在终端中,键入“ cd desktop”,然后输入$ pythoncon.py。如果没有错误,则说明您已连接MySQL服务器。祝好运!

On my mac os maverick i try this:

After that, enter in the python3 interpreter and type:

  1. import pymysql. If there is no error your installation is ok. For verification write a script to connect to mysql with this form:

  2. # a simple script for MySQL connection import pymysql db = pymysql.connect(host=”localhost”, user=”root”, passwd=”*”, db=”biblioteca”) #Sure, this is information for my db # close the connection db.close ()*

Give it a name (“con.py” for example) and save it on desktop. In Terminal type “cd desktop” and then $python con.py If there is no error, you are connected with MySQL server. Good luck!


回答 9

CyMySQL https://github.com/nakagami/CyMySQL

我已经在Windows 7上安装了pip,使用python 3.3只是pip install cymysql

(您不需要赛顿)快速而无痛

CyMySQL https://github.com/nakagami/CyMySQL

I have installed pip on my windows 7, with python 3.3 just pip install cymysql

(you don’t need cython) quick and painless


回答 10

这并不能完全回答我最初的问题,但我认为让所有人知道我的工作和原因很重要。

由于网络上普遍存在2.7示例和模块,因此我选择继续使用python 2.7而不是python 3。

现在,我同时使用mysqldb和mysql.connector连接到Python 2.7中的MySQL。两者都很棒并且运作良好。我认为mysql.connector从长远来看最终会更好。

This does not fully answer my original question, but I think it is important to let everyone know what I did and why.

I chose to continue using python 2.7 instead of python 3 because of the prevalence of 2.7 examples and modules on the web in general.

I now use both mysqldb and mysql.connector to connect to MySQL in Python 2.7. Both are great and work well. I think mysql.connector is ultimately better long term however.


回答 11

我在树莓派上通过python3使用cymysql,我只需通过以下方式安装:sudo pip3 install cython sudo pip3 install cymysql在没有cython的情况下,但应使cymysql更快

到目前为止,它的工作原理很吸引人,与MySQLdb非常相似

I’m using cymysql with python3 on a raspberry pi I simply installed by: sudo pip3 install cython sudo pip3 install cymysql where cython is not necessary but should make cymysql faster

So far it works like a charm and very similar to MySQLdb


回答 12

这是一个有关如何使Python 3.7与Mysql一起使用的快速教程,
感谢所有得到我问题解答的人
-希望有一天能对您有所帮助。
————————————————– –
我的系统:
Windows版本:Pro 64位

要求..下载并安装这些第一…
1.下载XAMPP ..
https://www.apachefriends.org/download.html
2.下载的Python
https://www.python.org/downloads/windows/

– ————
//方法
————–
安装完成后,请先安装xampp-安装Python 3.7。
完成两者的安装后-重新启动Windows系统。
现在启动xampp并从控制面板启动mysql服务器。
通过打开CMD并在终端类型中确认版本

c:\>cd c:\xampp\mysql\bin

c:\xampp\mysql\bin>mysql -h localhost -v
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.21-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

这是检查MYSQL版本

c:\xampp\mysql\bin>python
Python 3.7.0b3 (v3.7.0b3:4e7efa9c6f, Mar 29 2018, 18:42:04) [MSC v.1913 64 bit (AMD64)] on win32

这是要检查Python版本,
既然都已确认,请在CMD中输入以下内容…

c:\xampp\mysql\bin>pip install pymysql

pymysql安装完成后。
在桌面上或其他任何地方创建一个名为“ testconn.py”的新文件以进行快速访问。
使用sublime或其他文本编辑器打开此文件,并将其放入其中。
切记更改设置以反映您的数据库。

#!/usr/bin/python
import pymysql
pymysql.install_as_MySQLdb() 

import MySQLdb
db = MySQLdb.connect(user="yourusernamehere",passwd="yourpasswordhere",host="yourhosthere",db="yourdatabasehere")
cursor = db.cursor()
cursor.execute("SELECT * from yourmysqltablehere")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

现在在您的CMD中-输入

c:\Desktop>testconn.py

就是这样…您现在已从python脚本完全连接到mysql …
享受…

This is a quick tutorial on how to get Python 3.7 working with Mysql
Thanks to all from who I got answers to my questions
– hope this helps somebody someday.
—————————————————-
My System:
Windows Version: Pro 64-bit

REQUIREMENTS.. download and install these first…
1. Download Xampp..
https://www.apachefriends.org/download.html
2. Download Python
https://www.python.org/downloads/windows/

————–
//METHOD
————–
Install xampp first after finished installing – install Python 3.7.
Once finished installing both – reboot your windows system.
Now start xampp and from the control panel – start the mysql server.
Confirm the versions by opening up CMD and in the terminal type

c:\>cd c:\xampp\mysql\bin

c:\xampp\mysql\bin>mysql -h localhost -v
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.21-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

This is to check the MYSQL version

c:\xampp\mysql\bin>python
Python 3.7.0b3 (v3.7.0b3:4e7efa9c6f, Mar 29 2018, 18:42:04) [MSC v.1913 64 bit (AMD64)] on win32

This is to check the Python version
Now that both have been confirmed type the following into the CMD…

c:\xampp\mysql\bin>pip install pymysql

After the install of pymysql is completed.
create a new file called “testconn.py” on your desktop or whereever for quick access.
Open this file with sublime or another text editor and put this into it.
Remember to change the settings to reflect your database.

#!/usr/bin/python
import pymysql
pymysql.install_as_MySQLdb() 

import MySQLdb
db = MySQLdb.connect(user="yourusernamehere",passwd="yourpasswordhere",host="yourhosthere",db="yourdatabasehere")
cursor = db.cursor()
cursor.execute("SELECT * from yourmysqltablehere")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

Now in your CMD – type

c:\Desktop>testconn.py

And thats it… your now fully connected from a python script to mysql…
Enjoy…


回答 13

导入pymysql

打开数据库连接

db = pymysql.connect(“ localhost”,“ root”,“”,“装饰品”)

使用cursor()方法准备一个游标对象

cursor = db.cursor()

sql =“ SELECT * FROM项目”

cursor.execute(sql)

获取列表列表中的所有行。

结果=结果的cursor.fetchall():item_title = row [1]注释= row [2]打印(“项目标题为以下=%s,注释为以下=%s”%\(item_title,评论))

import pymysql

open database connection

db = pymysql.connect(“localhost”,”root”,””,”ornament”)

prepare a cursor object using cursor() method

cursor = db.cursor()

sql = “SELECT * FROM item”

cursor.execute(sql)

Fetch all the rows in a list of lists.

results = cursor.fetchall() for row in results: item_title = row[1] comment = row[2] print (“Title of items are the following = %s,Comments are the following = %s” % \ (item_title, comment))


使用Python插入MySQL数据库后,如何获得“ id”?

问题:使用Python插入MySQL数据库后,如何获得“ id”?

我执行INSERT INTO语句

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))

我想获取主键。

我的表有2列:

id      primary, auto increment
height  this is the other column.

我刚插入这个后,如何获得“ id”?

I execute an INSERT INTO statement

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))

and I want to get the primary key.

My table has 2 columns:

id      primary, auto increment
height  this is the other column.

How do I get the “id”, after I just inserted this?


回答 0

使用cursor.lastrowid得到插入光标对象的最后一行ID,或者connection.insert_id()从该连接上最后插入获取的ID。

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.


回答 1

另外,cursor.lastrowid(MySQLdb支持的dbapi / PEP249扩展名):

>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)

cursor.lastrowidconnection.insert_id()比另一次MySQL往返便宜,而且便宜很多。

Also, cursor.lastrowid (a dbapi/PEP249 extension supported by MySQLdb):

>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)

cursor.lastrowid is somewhat cheaper than connection.insert_id() and much cheaper than another round trip to MySQL.


回答 2

Python DBAPI规范还为光标对象定义了“ lastrowid”属性,因此…

id = cursor.lastrowid

…也应该起作用,并且显然基于每个连接。

Python DBAPI spec also define ‘lastrowid’ attribute for cursor object, so…

id = cursor.lastrowid

…should work too, and it’s per-connection based obviously.


回答 3

SELECT @@IDENTITY AS 'Identity';

要么

SELECT last_insert_id();
SELECT @@IDENTITY AS 'Identity';

or

SELECT last_insert_id();

如何在OSX 10.6中将MySQLdb与Python和Django一起使用?

问题:如何在OSX 10.6中将MySQLdb与Python和Django一起使用?

对于OSX 10.6用户,这是一个讨论很多的问题,但是我一直找不到能够解决问题的解决方案。这是我的设置:

Python 2.6.1 64位Django 1.2.1 MySQL 5.1.47 osx10.6 64位

我使用–no-site-packages创建了一个virtualenvwrapper,然后安装了Django。当我激活virtualenv并运行python manage.py syncdb时,出现以下错误:

Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

我还安装了MySQL for Python适配器,但无济于事(也许我安装不正确?)。

有人处理过吗?

This is a much discussed issue for OSX 10.6 users, but I haven’t been able to find a solution that works. Here’s my setup:

Python 2.6.1 64bit Django 1.2.1 MySQL 5.1.47 osx10.6 64bit

I create a virtualenvwrapper with –no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error:

Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I’ve also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?).

Anyone dealt with this before?


回答 0

我有同样的错误,pip install MySQL-python并为我解决了。

备用安装:

  • 如果您没有点子,easy_install MySQL-python应该可以。
  • 如果您的python是由打包系统管理的,则可能必须使用该系统(例如sudo apt-get install ...

下面,Soli指出如果收到以下错误:

EnvironmentError: mysql_config not found

…然后您还有另一个系统依赖性问题。解决方案因系统而异,但对于Debian衍生的系统:

sudo apt-get install python-mysqldb

I had the same error and pip install MySQL-python solved it for me.

Alternate installs:

  • If you don’t have pip, easy_install MySQL-python should work.
  • If your python is managed by a packaging system, you might have to use that system (e.g. sudo apt-get install ...)

Below, Soli notes that if you receive the following error:

EnvironmentError: mysql_config not found

… then you have a further system dependency issue. Solving this will vary from system to system, but for Debian-derived systems:

sudo apt-get install python-mysqldb


回答 1

运行Ubuntu,我必须做:

sudo apt-get install python-mysqldb

Running Ubuntu, I had to do:

sudo apt-get install python-mysqldb

回答 2

除了其他答案,以下内容还帮助我完成了mysql-python的安装:

virtualenv,mysql-python,pip:有人知道吗?

在Ubuntu上…

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

如果您没有适当的权限,请不要忘记在命令开头添加“ sudo”。

Adding to other answers, the following helped me finish the installation mysql-python:

virtualenv, mysql-python, pip: anyone know how?

On Ubuntu…

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

Don’t forget to add ‘sudo’ to the beginning of commands if you don’t have the proper permissions.


回答 3

试试下面的命令。他们为我工作:

brew install mysql-connector-c 
pip install MySQL-python

Try this the commands below. They work for me:

brew install mysql-connector-c 
pip install MySQL-python

回答 4

mysql_config必须在路上。在Mac上,执行

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

mysql_config must be on the path. On Mac, do

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

回答 5

pip install mysql-python

提出了一个错误:

EnvironmentError:找不到mysql_config

sudo apt-get install python-mysqldb

解决了问题。

pip install mysql-python

raised an error:

EnvironmentError: mysql_config not found

sudo apt-get install python-mysqldb

fixed the problem.


回答 6

我如何工作的:

virtualenv -p python3.5 env/test

在采购我的环境后:

pip install pymysql
pip install django

然后,我运行了startproject并在manage.py中添加了以下内容:

+ try:
+     import pymysql
+     pymysql.install_as_MySQLdb()
+ except:
+     pass

此外,还更新了此内部设置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foobar_db',
        'USER': 'foobaruser',
        'PASSWORD': 'foobarpwd',
    }
}

我也已经configparser==3.5.0在我的virtualenv中安装了,不确定是否需要…

希望能帮助到你,

How I got it working:

virtualenv -p python3.5 env/test

After sourcing my env:

pip install pymysql
pip install django

Then, I ran the startproject and inside the manage.py, I added this:

+ try:
+     import pymysql
+     pymysql.install_as_MySQLdb()
+ except:
+     pass

Also, updated this inside settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foobar_db',
        'USER': 'foobaruser',
        'PASSWORD': 'foobarpwd',
    }
}

I also have configparser==3.5.0 installed in my virtualenv, not sure if that was required or not…

Hope it helps,


回答 7

以下对我来说运行64位Ubuntu 13.10的完美工作:

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

现在,导航到您的virtualenv(例如env文件夹)并执行以下操作:

sudo ./bin/pip install mysql-python

实际上,我在另一个问题中找到了解决方案,并在下面引用了它:

如果使用–no-site-packages开关(默认设置)创建了virtualenv,则虚拟环境软件包中不包括系统范围内已安装的附加内容,例如MySQLdb。

您需要使用随virtualenv一起安装的pip命令安装MySQLdb。使用bin / activate脚本激活virtualenv,或者在virtualenv中使用bin / pip在本地安装MySQLdb库。

或者,使用–system-site-package开关创建包含系统站点包的新virtualenv。

我认为这也适用于OSX。唯一的问题是获得等效的安装命令libmysqlclient-devpython-dev因为mysql-python我猜它们是编译所必需的 。

希望这可以帮助。

The following worked perfectly for me, running Ubuntu 13.10 64-bit:

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

Now, navigate to your virtualenv (such as env folder) and execute the following:

sudo ./bin/pip install mysql-python

I actually found the solution in a separate question and I am quoting it below:

If you have created the virtualenv with the –no-site-packages switch (the default), then system-wide installed additions such as MySQLdb are not included in the virtual environment packages.

You need to install MySQLdb with the pip command installed with the virtualenv. Either activate the virtualenv with the bin/activate script, or use bin/pip from within the virtualenv to install the MySQLdb library locally as well.

Alternatively, create a new virtualenv with system site-packages included by using the –system-site-package switch.

I think this should also work with OSX. The only problem would be getting an equivalent command for installing libmysqlclient-dev and python-dev as they are needed to compile mysql-python I guess.

Hope this helps.


回答 8

试试这个:这为我解决了这个问题。

pip安装MySQL-python

Try this: This solved the issue for me .

pip install MySQL-python


回答 9

此问题是由于MySQL for Python适配器安装不完整/错误导致的。具体来说,我必须编辑mysql_config文件的路径以指向/ usr / local / mysql / bin / mysql_config-在本文中进行了详细讨论:http : //dakrauth.com/blog/entry/python-and- django-setup-mac-os-x-豹/

This issue was the result of an incomplete / incorrect installation of the MySQL for Python adapter. Specifically, I had to edit the path to the mysql_config file to point to /usr/local/mysql/bin/mysql_config – discussed in greater detail in this article: http://dakrauth.com/blog/entry/python-and-django-setup-mac-os-x-leopard/


回答 10

sudo apt-get install python-mysqldb 在ubuntu中完美工作

pip install mysql-python引发环境错误

sudo apt-get install python-mysqldb works perfectly in ubuntu

pip install mysql-python raises an Environment Error


回答 11

这适用于Red Hat Enterprise Linux Server 6.4版

sudo yum install mysql-devel
sudo yum install python-devel
pip install mysql-python

This worked for Red Hat Enterprise Linux Server release 6.4

sudo yum install mysql-devel
sudo yum install python-devel
pip install mysql-python

回答 12

您可以安装为 pip install mysqlclient

You can install as pip install mysqlclient


回答 13

我进行了OSX Mavericks和Pycharm 3的升级,并开始出现此错误,我使用了pip并易于安装,并得到了以下错误:

命令’/ usr / bin / clang’失败,退出状态为1。

所以我需要更新到Xcode 5,然后再次尝试使用pip进行安装。

pip install mysql-python

那解决了所有问题。

I made the upgrade to OSX Mavericks and Pycharm 3 and start to get this error, i used pip and easy install and got the error:

command’/usr/bin/clang’ failed with exit status 1.

So i need to update to Xcode 5 and tried again to install using pip.

pip install mysql-python

That fix all the problems.


回答 14

此处引发的错误是在导入python模块中。可以通过将python site-packages文件夹添加到OS X上的环境变量$ PYTHONPATH来解决。因此,我们可以将以下命令添加到.bash_profile文件中:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*用您正在使用的python版本替换xx

The error raised here is in importing the python module. This can be solved by adding the python site-packages folder to the environment variable $PYTHONPATH on OS X. So we can add the following command to the .bash_profile file:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*replace x.x with the python version you are using


回答 15

如果您使用的是python3,请尝试以下操作(我的操作系统是Ubuntu 16.04):

sudo apt-get install python3-mysqldb

If you are using python3, then try this(My OS is Ubuntu 16.04):

sudo apt-get install python3-mysqldb

回答 16

pip在Windows 8 64位系统上对我不起作用。 easy_install mysql-python为我工作。easy_install如果pip不起作用,您可以用来避免在Windows上生成二进制文件。

pip did not work for me on windows 8 64 bits system. easy_install mysql-python works for me. You can use easy_install to avoid building binaries on windows if pip does not work.


回答 17

我在OSX 10.6.6上遇到了相同的问题。但是,只是一个简单easy_install mysql-python的终端无法解决它,因为随之而来的另一个麻烦是:

error: command 'gcc-4.2' failed with exit status 1

显然,从XCode3(OSX 10.6附带提供)升级到XCode4后,就会出现此问题。此较新版本删除了对构建ppc拱的支持。如果相同,请尝试以下操作easy_install mysql-python

sudo bash
export ARCHFLAGS='-arch i386 -arch x86_64'
rm -r build
python setup.py build
python setup.py install

非常感谢Ned Deily的解决方案。在这里检查

I had the same problem on OSX 10.6.6. But just a simple easy_install mysql-python on terminal did not solve it as another hiccup followed:

error: command 'gcc-4.2' failed with exit status 1.

Apparently, this issue arises after upgrading from XCode3 (which is natively shipped with OSX 10.6) to XCode4. This newer ver removes support for building ppc arch. If its the same case, try doing as follows before easy_install mysql-python

sudo bash
export ARCHFLAGS='-arch i386 -arch x86_64'
rm -r build
python setup.py build
python setup.py install

Many thanks to Ned Deily for this solution. Check here


回答 18

对我来说,只需重新安装mysql-python即可解决问题

pip uninstall mysql-python
pip install mysql-python

For me the problem got solved by simply reinstalling mysql-python

pip uninstall mysql-python
pip install mysql-python

回答 19

安装命令行工具对我有用:

xcode-select --install

Install Command Line Tools Works for me:

xcode-select --install

回答 20

我通过MySQL-python使用pip安装库克服了相同的问题。当我第一次在settings.py中更改数据库设置并执行makemigrations命令时,可以看到控制台上显示的消息(解决方案遵循以下消息,请看一下)。

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

最后,我克服了以下问题:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s 
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$ 

I overcame the same problem by installing MySQL-python library using pip. You can see the message displayed on my console when I first changed my database settings in settings.py and executed makemigrations command(The solution is following the below message, just see that).

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Finally I overcame this problem as follows:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s 
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$ 

回答 21

运行此命令

sudo pip install mysql-python;

现在您可以运行命令了。

python manage.py startapp filename;

Run this command

sudo pip install mysql-python;

now you can run your command.

python manage.py startapp filename;

回答 22

我遇到了类似的情况,例如您在Mac OS X上的virtualenv中使用python3.7和django 2.1。尝试运行命令:

pip install mysql-python
pip install pymysql

__init__.py在您的项目文件夹中编辑文件,并添加以下内容:

import pymysql

pymysql.install_as_MySQLdb()

然后运行:python3 manage.py runserverpython manage.py runserver

I encountered similar situations like yours that I am using python3.7 and django 2.1 in virtualenv on mac osx. Try to run command:

pip install mysql-python
pip install pymysql

And edit __init__.py file in your project folder and add following:

import pymysql

pymysql.install_as_MySQLdb()

Then run: python3 manage.py runserver or python manage.py runserver


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

问题:如何使用pip安装Python MySQLdb模块?

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

How can I install the MySQLdb module for Python using pip?


回答 0

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

pip install mysqlclient

如果您需要1.2.x版本(仅限旧版Python),请使用 pip install 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

It’s easy to do, but hard to remember the correct spelling:

pip install mysqlclient

If you need 1.2.x versions (legacy Python only), use pip install MySQL-python

Note: Some dependencies might have to be in place when running the above command. Some hints on how to install these on various platforms:

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

Mac OS

brew install mysql-connector-c

if that fails, try

brew install mysql

回答 1

从全新的Ubuntu 14.04.2系统开始,需要以下两个命令:

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

仅仅进行“ pip安装”是行不通的。

http://codeinthehole.com/writing/how-to-set-up-mysql-for-python-on-ubuntu/

Starting from a fresh Ubuntu 14.04.2 system, these two commands were needed:

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

Just doing the “pip install” by itself did not work.

From http://codeinthehole.com/writing/how-to-set-up-mysql-for-python-on-ubuntu/


回答 2

第一

pip install pymysql

然后将下面的代码放入__init__.pyprojectname/__init__.py

import pymysql
pymysql.install_as_MySQLdb()

我的环境是(python3.5,django1.10),此解决方案对我有用!

希望这可以帮助!!

First

pip install pymysql

Then put the code below into __init__.py (projectname/__init__.py)

import pymysql
pymysql.install_as_MySQLdb()

My environment is (python3.5, django1.10) and this solution works for me!

Hope this helps!!


回答 3

我在通过Pip(问题编译源)在Windows上安装64位版本的MySQLdb时遇到问题[安装32位版本就可以了]。设法从http://www.lfd.uci.edu/~gohlke/pythonlibs/上的.whl文件安装已编译的MySQLdb

然后可以通过pip将.whl文件作为文档安装在https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels中

例如,如果您保存在中,C:/则可以通过

pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl

后续行动:如果您安装了64位版本的Python,那么您想通过上面的链接安装64位AMD版本的MySQLdb [即,即使您具有Intel处理器]。如果您改为尝试安装32位版本,我认为您会在下面的注释中得到不受支持的滚轮错误。

I had problems installing the 64-bit version of MySQLdb on Windows via Pip (problem compiling sources) [32bit version installed ok]. Managed to install the compiled MySQLdb from the .whl file available from http://www.lfd.uci.edu/~gohlke/pythonlibs/

The .whl file can then be installed via pip as document in https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels

For example if you save in C:/ the you can install via

pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl

Follow-up: if you have a 64bit version of Python installed, then you want to install the 64-bit AMD version of MySQLdb from the link above [i.e. even if you have a Intel processor]. If you instead try and install the 32-bit version, I think you get the unsupported wheel error in comments below.


回答 4

这对我有用:

pip install mysqlclient

这是针对python 3.x

well this worked for me:

pip install mysqlclient

this is for python 3.x


回答 5

我尝试了所有选项,但无法使其在Redhat平台上运行。我做了以下工作以使其工作:-

yum install MySQL-python -y

安装软件包后,便可以按照解释器中的说明导入模块:-

>>> import MySQLdb
>>> 

I tried all the option but was not able to get it working on Redhat platform. I did the following to make it work:-

yum install MySQL-python -y

Once the package was installed was able to import module as follows in the interpreter:-

>>> import MySQLdb
>>> 

回答 6

转到pycharm,然后转到默认设置-> pip(双击)-pymsqldb ..–>安装-在类似这样的程序中安装使用后

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

Go to pycharm then go to default setting –> pip (double click) — pymsqldb..– > install –after installing use in a program like this

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

回答 7

如果您使用的是Raspberry Pi [Raspbian OS]

首先需要有install pip命令

apt-get install python-pip

这样就可以依次安装

apt-get install python-dev libmysqlclient-dev

apt-get install python-pip

pip install MySQL-python

If you are use Raspberry Pi [Raspbian OS]

There are need to be install pip command at first

apt-get install python-pip

So that just install Sequently

apt-get install python-dev libmysqlclient-dev

apt-get install python-pip

pip install MySQL-python

回答 8

在此处输入图片说明

您可以访问此网站下载软件包。

enter image description here

You can go to this website to download the package.


回答 9

如果您无法安装mysqlclient,也可以安装pymysql

pip install pymysql

这与MySqldb相同。之后,使用pymysql代替MySQLdb

If you are unable to install mysqlclient you can also install pymysql:

pip install pymysql

This works same as MySqldb. After that use pymysql all over instead of MySQLdb


回答 10

我也遇到了同样的问题。如果您使用的是Windows,请按照以下步骤操作。转至:1.我的电脑2.系统属性3.高级系统设置4.在“高级”选项卡上,单击显示“环境变量”的按钮。5.然后在系统变量下,您必须添加/更改以下变量:PYTHONPATH和路径。这是我的变量的样子的粘贴信息:python path:

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

看到这个 链接以供参考

I had the same problem too.Follow these steps if you are on Windows. Go to: 1.My Computer 2.System Properties 3.Advance System Settings 4. Under the “Advanced” tab click the button that says “Environment Variables” 5. Then under System Variables you have to add / change the following variables: PYTHONPATH and Path. Here is a paste of what my variables look like: python path:

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

path:

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

See this link for reference


回答 11

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

例如,它需要一些与Visual Stdio相关的文件。一个解决方案是安装VS2008或2010……显然,这太昂贵了。

另一种方法是@ bob90937的答案。我在这里要做一些补充。

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

返回主题,我们可以选择MySQL-python(py2)Mysqlclient(py3) 并使用pip install 进行安装。它给我们带来了极大的便利!

The above answer is great, but there may be some problems when we using pip to install MySQL-python in Windows

for example,It needs some files that are associated with Visual Stdio .One solution is installing VS2008 or 2010……Obviously,it cost too much.

Another way is the answer of @bob90937 . I am here to do something to add.

with http://www.lfd.uci.edu/~gohlke/pythonlibs, u can download many Windows binaries of many scientific open-source extension packages for the official CPython distribution of the Python programming language.

Back to topic,we can choose the MySQL-python(py2) or Mysqlclient(py3) and use pip install to install. it gives us Great convenience!


回答 12

对于Python3,我需要这样做:

python3 -m pip install MySQL

For Python3 I needed to do this:

python3 -m pip install MySQL

回答 13


回答 14

在RHEL 7上:

sudo yum install yum-utils mariadb-devel python-pip python-devel gcc

sudo /bin/pip2 install MySQL-python

on RHEL 7:

sudo yum install yum-utils mariadb-devel python-pip python-devel gcc

sudo /bin/pip2 install MySQL-python


回答 15

如果您的系统上安装了Windows,请在cmd上键入以下命令:

pip install mysql-connector

如果以上命令不起作用,请尝试使用:

pip install mysql-connector-python

现在,如果上述命令无法完成工作,请尝试使用:

pip install mysql-connector-python-rf

就是这样,您现在就可以走了。

If you have Windows installed on your system then type the following command on cmd :

pip install mysql-connector

if the above command does not work try using:

pip install mysql-connector-python

Now,if the above commands do not get the work done, try using:

pip install mysql-connector-python-rf

That’s it you are good to go now.


回答 16

这里给出的许多答案都相当令人困惑,因此我将尝试简单地说一下。它帮助我安装了这个

pip install pymysql

然后在python文件中使用以下命令

import pymysql as MySQLdb

这样,您可以毫无问题地使用MySQLdb。

Many of the given answers here are quite confusing so I will try to put it simply. It helped me to install this

pip install pymysql

and then use the following command in the python file

import pymysql as MySQLdb

This way you can use MySQLdb without any problems.


回答 17

如果pip3不起作用,您可以尝试:

sudo apt install python3-mysqldb

If pip3 isn’t working, you can try:

sudo apt install python3-mysqldb

回答 18

我的环境是:

  • Windows 10专业版,
  • Python 3.7(python-3.7.1-amd64.exe),
  • MySQL 8.0(mysql-installer-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()

My environment are:

  • Windows 10 Pro,
  • Python 3.7 (python-3.7.1-amd64.exe),
  • MySQL 8.0 (mysql-installer-web-community-8.0.13.0.msi)

pip install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl

works for me.

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

回答 19

实际上,按照@Nick T的回答对我不起作用,我尝试apt-get install python-mysqldb为我工作

root@2fb0da64a933:/home/test_scrapy# apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libmariadbclient18 mysql-common
Suggested packages:
  default-mysql-server | virtual-mysql-server python-egenix-mxdatetime python-mysqldb-dbg
The following NEW packages will be installed:
  libmariadbclient18 mysql-common python-mysqldb
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 843 kB of archives.
After this operation, 4611 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 mysql-common all 5.8+1.0.2 [5608 B]
Get:2 http://deb.debian.org/debian stretch/main amd64 libmariadbclient18 amd64 10.1.38-0+deb9u1 [785 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 python-mysqldb amd64 1.3.7-1.1 [52.1 kB]                    
Fetched 843 kB in 23s (35.8 kB/s)                                                                                 
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package mysql-common.
(Reading database ... 13223 files and directories currently installed.)
Preparing to unpack .../mysql-common_5.8+1.0.2_all.deb ...
Unpacking mysql-common (5.8+1.0.2) ...
Selecting previously unselected package libmariadbclient18:amd64.
Preparing to unpack .../libmariadbclient18_10.1.38-0+deb9u1_amd64.deb ...
Unpacking libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Selecting previously unselected package python-mysqldb.
Preparing to unpack .../python-mysqldb_1.3.7-1.1_amd64.deb ...
Unpacking python-mysqldb (1.3.7-1.1) ...
Setting up mysql-common (5.8+1.0.2) ...
update-alternatives: using /etc/mysql/my.cnf.fallback to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Setting up libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Processing triggers for libc-bin (2.24-11+deb9u3) ...
Setting up python-mysqldb (1.3.7-1.1) ...
root@2fb0da64a933:/home/test_scrapy# python 
Python 2.7.13 (default, Nov 24 2017, 17:33:09) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> 

actually, follow @Nick T’s answer doesn’t work for me, i try apt-get install python-mysqldb work for me

root@2fb0da64a933:/home/test_scrapy# apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libmariadbclient18 mysql-common
Suggested packages:
  default-mysql-server | virtual-mysql-server python-egenix-mxdatetime python-mysqldb-dbg
The following NEW packages will be installed:
  libmariadbclient18 mysql-common python-mysqldb
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 843 kB of archives.
After this operation, 4611 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 mysql-common all 5.8+1.0.2 [5608 B]
Get:2 http://deb.debian.org/debian stretch/main amd64 libmariadbclient18 amd64 10.1.38-0+deb9u1 [785 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 python-mysqldb amd64 1.3.7-1.1 [52.1 kB]                    
Fetched 843 kB in 23s (35.8 kB/s)                                                                                 
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package mysql-common.
(Reading database ... 13223 files and directories currently installed.)
Preparing to unpack .../mysql-common_5.8+1.0.2_all.deb ...
Unpacking mysql-common (5.8+1.0.2) ...
Selecting previously unselected package libmariadbclient18:amd64.
Preparing to unpack .../libmariadbclient18_10.1.38-0+deb9u1_amd64.deb ...
Unpacking libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Selecting previously unselected package python-mysqldb.
Preparing to unpack .../python-mysqldb_1.3.7-1.1_amd64.deb ...
Unpacking python-mysqldb (1.3.7-1.1) ...
Setting up mysql-common (5.8+1.0.2) ...
update-alternatives: using /etc/mysql/my.cnf.fallback to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Setting up libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Processing triggers for libc-bin (2.24-11+deb9u3) ...
Setting up python-mysqldb (1.3.7-1.1) ...
root@2fb0da64a933:/home/test_scrapy# python 
Python 2.7.13 (default, Nov 24 2017, 17:33:09) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> 

使用pip安装特定的软件包版本

问题:使用pip安装特定的软件包版本

我正在尝试使用通过该--no-site-packages选项创建的新virtualenv安装MySQL_python适配器的1.2.2版本。PyPi中显示的当前版本是1.2.3。有没有办法安装旧版本?我发现有一篇文章指出应该这样做:

pip install MySQL_python==1.2.2

但是,安装后,它仍显示MySQL_python-1.2.3-py2.6.egg-info在站点包中。这是此软件包专用的问题,还是我做错了什么?

I’m trying to install version 1.2.2 of the MySQL_python adaptor, using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I found an article stating that this should do it:

pip install MySQL_python==1.2.2

When installed, however, it still shows MySQL_python-1.2.3-py2.6.egg-info in the site packages. Is this a problem specific to this package, or am I doing something wrong?


回答 0

TL; DR:

  • pip install -Iv(即pip install -Iv MySQL_python==1.2.2

首先,我发现您要执行的操作有两个问题。由于您已经安装了版本,因此应该卸载当前的现有驱动程序或使用pip install -I MySQL_python==1.2.2

但是,您很快就会发现这不起作用。如果您查看pip的安装日志,或者执行pip的安装日志,pip install -Iv MySQL_python==1.2.2则会发现PyPI URL链接不适用于MySQL_python v1.2.2。您可以在这里验证:http : //pypi.python.org/pypi/MySQL-python/1.2.2

由于sourceforge.net的最新升级和PyPI的过时URL,下载链接404s和后备URL链接正在无限重定向。

因此,要正确安装驱动程序,可以按照以下步骤操作:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

TL;DR:

  • pip install -Iv (i.e. pip install -Iv MySQL_python==1.2.2)

First, I see two issues with what you’re trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2

However, you’ll soon find out that this doesn’t work. If you look at pip’s installation log, or if you do a pip install -Iv MySQL_python==1.2.2 you’ll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2

The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net’s recent upgrade and PyPI’s stale URL.

So to properly install the driver, you can follow these steps:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

回答 1

您甚至可以在pip install命令中使用版本范围。像这样:

pip install 'stevedore>=1.3.0,<1.4.0'

如果该软件包已经安装,并且您想降级,请添加--force-reinstall以下内容:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

You can even use a version range with pip install command. Something like this:

pip install 'stevedore>=1.3.0,<1.4.0'

And if the package is already installed and you want to downgrade it add --force-reinstall like this:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

回答 2

一种方法,在提出这个职位,是提版本pip为:

pip install -Iv MySQL_python==1.2.2

即使用==并提及版本号以仅安装该版本。-I, --ignore-installed忽略已经安装的软件包。

One way, as suggested in this post, is to mention version in pip as:

pip install -Iv MySQL_python==1.2.2

i.e. Use == and mention the version number to install only that version. -I, --ignore-installed ignores already installed packages.


回答 3

要安装特定的python软件包版本,无论是第一次,升级还是降级,请使用:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python版本1.2.2不可用,因此我使用了其他版本。要从索引查看所有可用的软件包版本,请排除该版本:

pip install MySQL_python==

To install a specific python package version whether it is the first time, an upgrade or a downgrade use:

pip install --force-reinstall MySQL_python==1.2.4

MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:

pip install MySQL_python==

回答 4

我相信,如果您已经安装了软件包,pip不会用其他版本覆盖它。使用-I忽略以前的版本。

I believe that if you already have a package it installed, pip will not overwrite it with another version. Use -I to ignore previous versions.


回答 5

有时,先前安装的版本会被缓存。

~$ pip install pillow==5.2.0

它返回以下内容:
已满足要求:/home/ubuntu/anaconda3/lib/python3.6/site-packages(5.2.0)中的pillow == 5.2.0

我们可以将–no-cache-dir与-I一起使用来覆盖它

~$ pip install --no-cache-dir -I pillow==5.2.0

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use –no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

回答 6

由于这似乎是pip版本10中引入的重大更改,因此我降级为兼容版本:

pip install 'pip<10' 

该命令告诉pip安装低于版本10的模块版本。在virutalenv中执行此操作,这样就不会增加Python站点安装的麻烦

Since this appeared to be a breaking change introduced in version 10 of pip, I downgraded to a compatible version:

pip install 'pip<10' 

This command tells pip to install a version of the module lower than version 10. Do this in a virutalenv so you don’t screw up your site installation of Python.


回答 7

我最近在使用想要记录到某处pip-I标志时遇到问题:

-I卸载继续之前的现有的包; 它将仅安装在旧版本的顶部。这意味着应将两个版本之间应删除的所有文件保留在原处。如果这些文件与其他已安装模块共享名称,则可能导致奇怪的行为。

例如,假设有一个名为的软件包package。在的一个package文件中,他们使用import datetime。现在,在中package@2.0.0,它指向标准库datetime模块,但是在中package@3.0.0,他们添加了本地语言datetime.py以替代标准库版本(无论出于何种原因)。

现在说我跑步pip install package==3.0.0,但后来意识到我实际上想要版本2.0.0。如果我现在运行pip install -I package==2.0.0datetime.py文件将不会被删除,因此任何调用import datetime都会导入错误的模块。

就我而言,这表现为奇怪的语法错误,因为该软件包的较新版本添加了仅与Python 3兼容的文件,并且当我将软件包版本降级以支持Python 2时,我继续导入仅Python-3模块。

基于此,我认为-I在更新已安装的软件包版本时,总是比使用旧软件包更可取。

I recently ran into an issue when using pip‘s -I flag that I wanted to document somewhere:

-I will not uninstall the existing package before proceeding; it will just install it on top of the old one. This means that any files that should be deleted between versions will instead be left in place. This can cause weird behavior if those files share names with other installed modules.

For example, let’s say there’s a package named package. In one of packages files, they use import datetime. Now, in package@2.0.0, this points to the standard library datetime module, but in package@3.0.0, they added a local datetime.py as a replacement for the standard library version (for whatever reason).

Now lets say I run pip install package==3.0.0, but then later realize that I actually wanted version 2.0.0. If I now run pip install -I package==2.0.0, the old datetime.py file will not be removed, so any calls to import datetime will import the wrong module.

In my case, this manifested with strange syntax errors because the newer version of the package added a file that was only compatible with Python 3, and when I downgraded package versions to support Python 2, I continued importing the Python-3-only module.

Based on this, I would argue that uninstalling the old package is always preferable to using -I when updating installed package versions.


回答 8

下面的命令对我有用

Python版本-2.7

包-python-jenkins

命令- $ pip install 'python-jenkins>=1.1.1'

This below command worked for me

Python version – 2.7

package – python-jenkins

command – $ pip install 'python-jenkins>=1.1.1'


回答 9

您可以通过两种方式安装任何版本的软件包: -A)。pip install -Iv软件包名称==版本 B)。pip install -v软件包名称==版本

为一个

在这里,如果您在安装时使用-I选项(当您不知道该软件包是否已安装时)(例如’pip install -Iv pyreadline == 2. *’之类的东西),则您将在安装新的单独的程序包,而相同的现有程序包具有不同的版本。

对于B

  1. 首先,您可能要检查是否有违反要求的情况。 点子检查

2.然后查看点子列表已经安装了什么

3.如果软件包列表中包含您要安装的特定版本的软件包,那么更好的选择是先通过pip uninstall package-name卸载该版本的软件包。

4.现在,您可以继续通过pip install -v package-name == version重新安装具有特定版本的相同软件包, 例如pip install -v pyreadline == 2. *

There are 2 ways you may install any package with version:- A). pip install -Iv package-name == version B). pip install -v package-name == version

For A

Here, if you’re using -I option while installing(when you don’t know if the package is already installed) (like ‘pip install -Iv pyreadline == 2.* ‘or something), you would be installing a new separate package with the same existing package having some different version.

For B

  1. At first, you may want to check for no broken requirements. pip check

2.and then see what’s already installed by pip list

3.if the list of the packages contain any package that you wish to install with specific version then the better option is to uninstall the package of this version first, by pip uninstall package-name

4.And now you can go ahead to reinstall the same package with a specific version, by pip install -v package-name==version e.g. pip install -v pyreadline == 2.*


回答 10

如果要更新为最新版本,但您不知道可以输入的是最新版本。

pip安装MySQL_python –upgrade

这将更新可用的最新版本的MySQL_python,您可以将其用于任何其他软件包版本。

If you want to update to latest version and you don’t know what is the latest version you can type.

pip install MySQL_python –upgrade

This will update the MySQL_python for latest version available, you can use for any other package version.


如何使用Python连接到MySQL数据库?

问题:如何使用Python连接到MySQL数据库?

如何使用python程序连接到MySQL数据库?

How do I connect to a MySQL database using a python program?


回答 0

分三步使用Python 2连接到MYSQL

1-设定

在执行任何操作之前,必须安装MySQL驱动程序。与PHP不同,默认情况下,Python仅安装SQLite驱动程序。最常用的软件包是MySQLdb,但很难使用easy_install进行安装。请注意,MySQLdb仅支持Python 2。

对于Windows用户,您可以获取MySQLdbexe

对于Linux,这是一个临时包(python-mysqldb)。(您可以在命令行中使用sudo apt-get install python-mysqldb(对于基于debian的发行版),yum install MySQL-python(对于基于rpm的dnf install python-mysql发行版)或(对于现代的fedora发行版)进行下载。)

对于Mac,您可以使用Macport安装MySQLdb

2-用法

安装后,重新启动。这不是强制性的,但是如果出现问题,它将阻止我回答本文中的3个或4个其他问题。因此,请重新启动。

然后,就像使用其他任何软件包一样:

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

当然,有成千上万种可能性和选择。这是一个非常基本的例子。您将不得不查看文档。一个良好的起点

3-更高级的用法

了解了它的工作原理后,您可能希望使用ORM来避免手动编写SQL并像处理Python对象一样处理表。Python社区中最著名的ORM是SQLAlchemy

我强烈建议您使用它:您的生活将变得更加轻松。

我最近在Python世界中发现了另一种宝石:peewee。这是一个非常精简的ORM,非常易于安装和使用。对于小型项目或独立应用程序来说,这让我感到欣慰,而在使用SQLAlchemy或Django之类的大型工具的时候就显得过分了:

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

本示例开箱即用。除了带有peewee(pip install peewee)外,没有其他要求。

Connecting to MYSQL with Python 2 in three steps

1 – Setting

You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it’s hard to install it using easy_install. Please note MySQLdb only supports Python 2.

For Windows user, you can get an exe of MySQLdb.

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

For Mac, you can install MySQLdb using Macport.

2 – Usage

After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using any other package :

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

3 – More advanced usage

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

I strongly advise you to use it: your life is going to be much easier.

I recently discovered another jewel in the Python world: peewee. It’s a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

This example works out of the box. Nothing other than having peewee (pip install peewee) is required.


回答 1

这是使用MySQLdb的一种方法,该方法仅支持Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

这里参考

Here’s one way to do it, using MySQLdb, which only supports Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

Reference here


回答 2

Oracle(MySQL)现在支持纯Python连接器。这意味着无需安装任何二进制文件:它只是一个Python库。它称为“连接器/ Python”。

http://dev.mysql.com/downloads/connector/python/

Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it’s just a Python library. It’s called “Connector/Python”.

http://dev.mysql.com/downloads/connector/python/


回答 3

如果您不需要MySQLdb,但是可以接受任何库,那么我将非常非常推荐MySQL的MySQL Connector / Python:http : //dev.mysql.com/downloads/connector/python/

它是一个软件包(大约110k),是纯Python,因此它与系统无关,并且安装非常简单。您只需下载,双击,确认许可协议即可。无需Xcode,MacPorts,编译,重新启动……

然后,您像这样连接:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')

try:
   cursor = cnx.cursor()
   cursor.execute("""
      select 3 from your_table
   """)
   result = cursor.fetchall()
   print result
finally:
    cnx.close()

If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/.

It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting …

Then you connect like:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')

try:
   cursor = cnx.cursor()
   cursor.execute("""
      select 3 from your_table
   """)
   result = cursor.fetchall()
   print result
finally:
    cnx.close()

回答 4

如果要避免安装mysql标头只是为了从python访问mysql,请停止使用MySQLDb。

使用pymysql。它可以完成MySQLDb的所有工作,但是它完全是在Python中实现的,没有外部依赖项。这使所有操作系统上的安装过程一致且容易。 pymysql是代替MySQLDb和恕我直言的替代品,没有理由将MySQLDb用于任何用途…永远!- PTSD from installing MySQLDb on Mac OSX and *Nix systems,但那只是我。

安装

pip install pymysql

就这样…您已经准备好玩了。

pymysql Github仓库的示例用法

import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

还-快速,透明地替换现有代码中的MySQLdb

如果您已有使用MySQLdb的代码,则可以使用以下简单过程将其轻松替换为pymysql:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

所有后续对MySQLdb的引用将透明地使用pymysql。

Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.

Use pymysql. It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies. This makes the installation process on all operating systems consistent and easy. pymysql is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything… EVER! – PTSD from installing MySQLDb on Mac OSX and *Nix systems, but that’s just me.

Installation

pip install pymysql

That’s it… you are ready to play.

Example usage from pymysql Github repo

import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

ALSO – Replace MySQLdb in existing code quickly and transparently

If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

All subsequent references to MySQLdb will use pymysql transparently.


回答 5

尝试使用MySQLdb。MySQLdb仅支持Python 2。

这里有一个如何分页的方法:http : //www.kitebird.com/articles/pydbapi.html


从页面:

# server_version.py - retrieve and display database server version

import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

Try using MySQLdb. MySQLdb only supports Python 2.

There is a how to page here: http://www.kitebird.com/articles/pydbapi.html


From the page:

# server_version.py - retrieve and display database server version

import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

回答 6

作为数据库驱动程序,还有oursql。该链接上列出的一些原因说明了为什么我们的sql更好:

  • oursql具有真正的参数化功能,可将SQL和数据完全分别发送到MySQL。
  • oursql允许将文本或二进制数据流式传输到数据库中并从数据库中流式传输出来,而不需要将所有内容都缓存在客户端中。
  • oursql既可以延迟插入行,也可以延迟获取行。
  • oursql默认情况下启用unicode支持。
  • oursql支持python 2.4到2.7,在2.6+上没有任何弃用警告(请参阅PEP 218),在2.7上也没有完全失败(请参阅PEP 328)。
  • oursql在python 3.x上本地运行。

那么如何使用oursql连接到mysql?

与mysqldb非常相似:

import oursql

db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
    print row[0]

文档中教程相当不错。

当然,对于ORM,SQLAlchemy是一个不错的选择,正如其他答案中已经提到的那样。

As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:

  • oursql has real parameterization, sending the SQL and data to MySQL completely separately.
  • oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
  • oursql can both insert rows lazily and fetch rows lazily.
  • oursql has unicode support on by default.
  • oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
  • oursql runs natively on python 3.x.

So how to connect to mysql with oursql?

Very similar to mysqldb:

import oursql

db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
    print row[0]

The tutorial in the documentation is pretty decent.

And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.


回答 7

在终端中运行以下命令以安装mysql连接器:

pip install mysql-connector-python

并在python编辑器中运行此命令以连接到MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

执行MySQL命令的示例(在python edior中):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert or update

有关更多命令:https : //www.w3schools.com/python/python_mysql_getstarted.asp

Run this command in your terminal to install mysql connector:

pip install mysql-connector-python

And run this in your python editor to connect to MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

Samples to execute MySQL Commands (in your python edior):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert or update

For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp


回答 8

SqlAlchemy的


SQLAlchemy是Python SQL工具箱和对象关系映射器,它为应用程序开发人员提供了SQL的全部功能和灵活性。SQLAlchemy提供了一整套著名的企业级持久性模式,旨在用于高效和高性能的数据库访问,并被适配为简单的Pythonic域语言。

安装

pip install sqlalchemy

RAW查询

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

ORM方式

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()

SqlAlchemy


SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

Installation

pip install sqlalchemy

RAW query

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

ORM way

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()

回答 9

尽管有上述所有答案,但是如果您不想预先连接到特定的数据库,例如,如果您仍要创建数据库(!),则可以使用connection.select_db(database),如下所示。

import pymysql.cursors
connection = pymysql.connect(host='localhost',
                         user='mahdi',
                         password='mahdi',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()

Despite all answers above, in case you do not want to connect to a specific database upfront, for example, if you want to create the database still (!), you can use connection.select_db(database), as demonstrated in the following.

import pymysql.cursors
connection = pymysql.connect(host='localhost',
                         user='mahdi',
                         password='mahdi',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()

回答 10

MySQLdb是直接的方法。您可以通过连接执行SQL查询。期。

我首选的方法也是pythonic,而是使用强大的SQLAlchemy。这是与查询相关的教程,这是有关SQLALchemy的ORM功能的教程。

MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.


回答 11

对于Python3.6,我发现了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能并得到了结果:mysqlclient更快。

以下是我的测试过程(需要安装python lib profilehooks来分析时间流逝:

原始SQL: select * from FOO;

在mysql终端中立即执行: 46410 rows in set (0.10 sec)

pymysql(2.4秒):

from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_pymysql():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_pymysql()

这是pymysql配置文件: 在此处输入图片说明


mysqlclient(0.4秒)

from profilehooks import profile
import MySQLdb

connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_mysqlclient():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_mysqlclient()

这是mysqlclient配置文件: 在此处输入图片说明

因此,似乎mysqlclient比pymysql快得多

for Python3.6 I found two driver: pymysql and mysqlclient. I tested the performance between them and got the result: the mysqlclient is faster.

below is my test process(need install python lib profilehooks to analyze time elapse:

raw sql: select * from FOO;

immediatly execute in mysql terminal: 46410 rows in set (0.10 sec)

pymysql (2.4s):

from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_pymysql():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_pymysql()

here’s the pymysql profile: enter image description here


mysqlclient (0.4s)

from profilehooks import profile
import MySQLdb

connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_mysqlclient():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_mysqlclient()

here’s the mysqlclient profile: enter image description here

So, it seems that mysqlclient is much faster than pymysql


回答 12

从python连接到MySQL的最佳方法是使用MySQL Connector / Python,因为它是MySQL的正式Oracle驱动程序,可与Python一起使用,并且可与Python 3和Python 2一起使用。

按照下面提到的步骤连接MySQL

  1. 使用pip安装连接器

    pip install mysql-connector-python

或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序

  1. 使用connect()mysql连接器python的method连接到MySQL。将所需的参数传递给connect()method。即主机,用户名,密码和数据库名称。

  2. cursorconnect()方法返回的连接对象创建对象以执行SQL查询。

  3. 工作完成后,关闭连接。

范例

import mysql.connector
 from mysql.connector import Error
 try:
     conn = mysql.connector.connect(host='hostname',
                         database='db',
                         user='root',
                         password='passcode')
     if conn.is_connected():
       cursor = conn.cursor()
       cursor.execute("select database();")
       record = cursor.fetchall()
       print ("You're connected to - ", record)
 except Error as e :
    print ("Print your error msg", e)
 finally:
    #closing database connection.
    if(conn.is_connected()):
       cursor.close()
       conn.close()

参考-https: //pynative.com/python-mysql-database-connection/

MySQL Connector Python的重要API

  • 对于DML操作-使用cursor.execute()cursor.executemany()运行查询。并connection.commit()用于保留对数据库的更改之后

  • 要获取数据-使用cursor.execute()运行查询cursor.fetchall()cursor.fetchone()cursor.fetchmany(SIZE)获取数据

Best way to connect to MySQL from python is to Use MySQL Connector/Python because it is official Oracle driver for MySQL for working with Python and it works with both Python 3 and Python 2.

follow the steps mentioned below to connect MySQL

  1. install connector using pip

    pip install mysql-connector-python

or you can download the installer from https://dev.mysql.com/downloads/connector/python/

  1. Use connect() method of mysql connector python to connect to MySQL.pass the required argument to connect() method. i.e. Host, username, password, and database name.

  2. Create cursor object from connection object returned by connect()method to execute SQL queries.

  3. close the connection after your work completes.

Example:

import mysql.connector
 from mysql.connector import Error
 try:
     conn = mysql.connector.connect(host='hostname',
                         database='db',
                         user='root',
                         password='passcode')
     if conn.is_connected():
       cursor = conn.cursor()
       cursor.execute("select database();")
       record = cursor.fetchall()
       print ("You're connected to - ", record)
 except Error as e :
    print ("Print your error msg", e)
 finally:
    #closing database connection.
    if(conn.is_connected()):
       cursor.close()
       conn.close()

Reference – https://pynative.com/python-mysql-database-connection/

Important API of MySQL Connector Python

  • For DML operations – Use cursor.execute() and cursor.executemany() to run query. and after this use connection.commit() to persist your changes to DB

  • To fetch data – Use cursor.execute() to run query and cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE) to fetch data


回答 13

只是以上答案的修改。只需运行此命令即可为python安装mysql

sudo yum install MySQL-python
sudo apt-get install MySQL-python

记得!区分大小写。

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.


回答 14

mysqlclient是最好的,因为其他人仅提供对特定版本的python的支持

 pip install mysqlclient

示例代码

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

参见https://github.com/PyMySQL/mysqlclient-python

mysqlclient is the best as others only provide support to specific versions of python

 pip install mysqlclient

example code

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

see https://github.com/PyMySQL/mysqlclient-python


回答 15

尽管有些人可能标志着其视为重复和生气,我复制别人的答案,我真的想强调Napik先生的回应的一个方面。因为错过了,导致全国网站停机(9分钟)。如果只有某人共享此信息,则可以避免!

这是他的代码:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
try:
   cursor = cnx.cursor()
   cursor.execute("""select 3 from your_table""")
   result = cursor.fetchall()
   print(result)
finally:
    cnx.close()

这里重要的是Try and Final子句。这允许始终连接,无论代码的游标/ sqlstatement部分发生了什么,都可以关闭与之的。许多活动的连接会导致DBLoadNoCPU尖峰,并可能导致数据库服务器崩溃。

我希望此警告有助于节省服务器并最终节省工作!:D

Even though some of you may mark this as a duplicate and get upset that I am copying someone else’s answer, I would REALLY like to highlight an aspect of Mr. Napik’s response. Because I missed this, I caused nationwide website downtime (9min). If only someone shared this information, I could have prevented it!

Here is his code:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
try:
   cursor = cnx.cursor()
   cursor.execute("""select 3 from your_table""")
   result = cursor.fetchall()
   print(result)
finally:
    cnx.close()

The important thing here is the Try and Finally clause. This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code. A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.

I hope this warning helps to save servers and ultimately jobs! :D


回答 16

也看看暴风雨。它是一个简单的SQL映射工具,可让您轻松编写和创建SQL条目,而无需编写查询。

这是一个简单的示例:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

查找并反对使用:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

使用主键查找:

print store.get(User, 1).name #Mark

有关更多信息,请参见教程

Also take a look at Storm. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.

Here is a simple example:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

To find and object use:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

Find with primary key:

print store.get(User, 1).name #Mark

For further information see the tutorial.


回答 17

这是Mysql DB连接

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST']) 
def index():
    if request.method == "POST":
        details = request.form
        cur = mysql.connection.cursor()
        cur.execute ("_Your query_")
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

This is Mysql DB connection

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST']) 
def index():
    if request.method == "POST":
        details = request.form
        cur = mysql.connection.cursor()
        cur.execute ("_Your query_")
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

回答 18

首先安装驱动程序

pip install MySQL-python   

然后,基本代码如下所示:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 

first install the driver

pip install MySQL-python   

Then a basic code goes like this:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 

回答 19

您可以通过这种方式将python代码连接到mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

you can connect your python code to mysql in this way.

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

回答 20

首先安装驱动程序(Ubuntu)

  • 须藤apt-get install python-pip

  • sudo pip install -U pip

  • 须藤apt-get install python-dev libmysqlclient-dev

  • sudo apt-get安装MySQL-python

MySQL数据库连接代码

import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

First install the driver (Ubuntu)

  • sudo apt-get install python-pip

  • sudo pip install -U pip

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

  • sudo apt-get install MySQL-python

MySQL database connection codes

import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

回答 21

对于python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

我在Windows 7上安装了pip,只需pip install cymysql

(您不需要赛顿)快速而无痛

For python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

I have pip installed on my windows 7, just pip install cymysql

(you don’t need cython) quick and painless


回答 22

首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器

在Python控制台上输入:

pip install mysql-connector-python-rf
import mysql.connector

First, install python-mysql connector from https://dev.mysql.com/downloads/connector/python/

on Python console enter:

pip install mysql-connector-python-rf
import mysql.connector