简单的Python-MySQL桥梁?
Python和MySQL之间有一个很好很简单的界面吗?我查看了MySQLdb模块,SQLAlchemy和MySQL提供的模块。他们工作,但只是笨重,难以快速合作。我是Python新手,但我已经在MATLAB中完成了这个工作,并且他们有一个非常简单的界面。 I.E.简单的Python-MySQL桥梁?
要执行在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)一样简单:
[Fn,Ln,Hd] = mysql(['SELECT first_name, last_name, hire_date FROM employees WHERE hire_date = ',num2str(some_date)])
没有游标和连接,使每次查询的时候,只是一个简单的I/O查询执行器和数据还者,我喜欢与数据库玩,有很多交叉。平台项目一目了然地连接并查看MATLAB中的数据是一项非常棒的功能。有没有一个Python桥梁来做到这一点?
当然,你可以这样写
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
和database
发电机被硬编码到函数。 MATLAB也必须将这些参数存储在某个地方。
你可以拉username
和database
出作为额外的参数,但随后你回笼复杂的同级别 - 而不能够有超过连接池控制优势等
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()
因此,要获得我们从程序处理大量的数据库查询所需要的性能,我们需要至少传递
def do_mysql(cnx, query, *args):
cursor = cnx.cursor()
cursor.execute(query, args)
for result in cursor:
yield result
cursor.close()
阿的连接,现在有没有任何真正的胆量了此功能和所有代码的参数部分已被推回给调用者
+1了解如何自己提取复杂性。谢谢!如果没有其他答案出现,我会在一两天内检查它。 –
有一个SQLAlchemy的扩展名为SqlSoup它不需要对大部分设置的:
from sqlalchemy.ext.sqlsoup import SqlSoup
db = SqlSoup('mysql://scott:[email protected]/employees')
然后运行一个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
或者,如果你只想要一个结果,使用相同的db.execute
呼叫,则:
您还可以使用SQLAlchemy的功能,如它的query syntax而不是编写SQL。
不知道关于sqlsoup。 +1 –
从来没有听说过它,我会检查出来。非常感激! –
您仍然必须提供MySQL数据库*的某处*的连接信息。 – Amber