简单的PythonMySQL桥?

2024-05-13 23:03:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python和MySQL之间有没有一个漂亮而简单的接口?我已经看过MySQLdb模块、SQLAlchemy和MySQL提供的模块。他们工作,但只是笨重和难以快速工作。我是Python的新手,但我在MATLAB中做过这个,而且它们有一个非常简单的界面。一、 E

每次要用Python执行查询时,似乎必须执行以下操作:

import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
     "WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()

而在MATLAB中,我只启动一次连接(比如启动程序时,然后检索的内容很简单(from here):

^{pr2}$

无需每次查询时创建游标和连接,只需一个简单的I/O查询执行器和数据返回器。我喜欢玩数据库,有很多跨平台的项目。能够在MATLAB中即时连接和查看数据是一个很棒的特性。有没有Python桥可以做到这一点?在


Tags: 模块nameimportconnectordatetimedatemysqlcursor
3条回答

使用熊猫。它的界面很棒。看这里:

python-pandas and databases like mysql

我用它从python访问我所有的数据库。在

有一个名为SqlSoup的SQLAlchemy扩展,它消除了大部分设置的需要:

from sqlalchemy.ext.sqlsoup import SqlSoup
db = SqlSoup('mysql://scott:mypassword@localhost/employees')

然后,要运行SQL查询,请参阅SqlSoup文档的raw SQL section

^{pr2}$

或者,如果只需要一个结果,请使用相同的db.execute调用,然后:

name, email = rp.fetchone()

您还可以使用SQLAlchemy的特性,比如它是query syntax,而不是编写SQL。在

当然,你可以写一个这样的生成器

import datetime
import mysql.connector

def do_mysql(query, *args):
    cnx = mysql.connector.connect(user='scott', database='employees')
    cursor = cnx.cursor()
    cursor.execute(query, args)
    for result in cursor:
        yield result
    cursor.close()
    cnx.close()

但是现在username和{}被硬编码到函数中。MATLAB也必须将这些参数存储在某个地方。在

您可以将usernamedatabase作为额外的参数拉出,但之后您将返回到相同的复杂程度—没有能够控制连接池等优点

^{pr2}$

因此,为了从处理大量数据库查询的程序中获得所需的性能,我们至少需要传入连接

def do_mysql(cnx, query, *args):
    cursor = cnx.cursor()
    cursor.execute(query, args)
    for result in cursor:
        yield result
    cursor.close()

啊,现在这个函数真的没有任何胆量了,代码的所有参数部分都被推回到调用者那里了

相关问题 更多 >