简体   繁体   English

简单的Python-MySQL桥?

[英]Simple Python-MySQL Bridge?

Is there a nice and simple interface between Python and MySQL? Python和MySQL之间有一个漂亮而简单的接口吗? I've looked at MySQLdb module, SQLAlchemy, and the module provided by MySQL. 我查看了MySQLdb模块,SQLAlchemy和MySQL提供的模块。 They work, but are just clunky and difficult to quickly work with. 他们工作,但只是笨重,很难快速合作。 I'm brand new to Python, but I've done this in MATLAB and they have an incredibly easy interface. 我是Python的新手,但我在MATLAB中做到了这一点,他们有一个非常简单的界面。 IE IE

Every time you want to perform a query in Python it seems like you have to do something like: 每次要在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()

Whereas in MATLAB, I initiate the connection once (like when starting up the program, and then retrieving something is as simple as ( from here ): 在MATLAB中,我启动连接一次(比如启动程序时,然后检索某些东西就像( 从这里 )一样简单:

[Fn,Ln,Hd] = mysql(['SELECT first_name, last_name, hire_date FROM employees WHERE hire_date = ',num2str(some_date)])

No cursors and connections to make every time you query, just a simple I/O query executer and data returner. 每次查询时都没有游标和连接,只需一个简单的I / O查询执行器和数据返回器。 I like playing with databases and have many cross-platform projects. 我喜欢玩数据库,有很多跨平台的项目。 Being able to instantly connect to and look at data in MATLAB is an awesome feature. 能够在MATLAB中即时连接和查看数据是一个很棒的功能。 Is there a Python bridge to do this? 有没有Python桥来做到这一点?

Use Pandas. 使用熊猫。 It has a great interface. 它有一个很棒的界面。 Look here: 看这里:

python-pandas and databases like mysql python-pandas和mysql这样的数据库

I use it to access all my databases from python. 我用它来从python访问我的所有数据库。

There's an SQLAlchemy extension called SqlSoup which removes the need for most of the setup: 有一个名为SqlSoup的SQLAlchemy扩展,它不需要大多数设置:

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

Then to run an SQL query, see the raw SQL section of the SqlSoup docs: 然后运行SQL查询,请参阅SqlSoup文档的原始SQL部分

rp = db.execute('select name, email from users where name like :name order by name', name='%Bhargan%')
for name, email in rp.fetchall():
    print name, email

Or if you only want one result, use the same db.execute call, then: 或者,如果您只想要一个结果,请使用相同的db.execute调用,然后:

name, email = rp.fetchone()

You can also use SQLAlchemy's features, like it's query syntax instead of writing SQL. 您还可以使用SQLAlchemy的功能,例如查询语法而不是编写SQL。

Sure, you could write a generator like this 当然,你可以写一个像这样的发电机

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

But now the username and database are hardcoded into the function. 但现在usernamedatabase被硬编码到函数中。 MATLAB must have these parameters stored somewhere too though. MATLAB必须将这些参数存储在某处。

You could pull the username and database out as extra parameters, but then you are heading back to the same level of complexity - without the advantages of being able to have control over connection pooling, etc. 您可以将usernamedatabase作为额外参数拉出,但随后您将返回到相同级别的复杂性 - 没有能够控制连接池等优点。

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

So to get the performance we need from a program handling lots of database queries, we'll need to at least pass the connection in 因此,为了从处理大量数据库查询的程序中获得所需的性能,我们至少需要传递连接

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

Ah, now there's not really any guts to this function and all the parametric parts of the code have been pushed back out to the caller 啊,现在对这个功能没有任何胆量,代码的所有参数部分都被推回到调用者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM