Pandas中用with结构与MySQL数据库交互

来源:互联网 发布:淘宝网账户被冻结 编辑:程序博客网 时间:2024/06/05 23:03

Python中,with可以让代码更简练,若产生异常,清理工作更简单

Pandas中使用to_sql和read_sql数据库进行数据交换,一般的代码中,我们都要先建立连接connect,然后使用to_sql或者read_sql。为了防止异常中断整个程序,往往使用try语句保证程序正常运行。

如果追求更加Pythonic的代码,可以用with结构来使代码更加精简
我最初模仿with open as 的结构,尝试的代码是这样的

对于read_sql来说

import MySQLdbsql = '*************'with MySQLdb.connect(ip, user, password, dbname, charset='utf8') as conn:    res = pd.read_sql(sql, conn)

是我把关闭文件的close()跟关闭数据库连接的close()混淆了
百度了半天之后,在一位大神的博客里找到了方法(写这篇博文的时候,回去找那个博客却找不到了)

import MySQLdbfrom contextlib import closingsql = '*************'with closing(MySQLdb.connect(ip, user, password, dbname, charset='utf8')) as conn:    res = pd.read_sql(sql, conn)

我看了一些技术文章,都是用sqlalchemy,pymysql/mysql.connector来读取MySQL中的数据,例如在http://www.itkeyword.com/doc/2039969901128520x595/writing-to-mysql-database-with-pandas-using-sqlalchemy-to-sql 看到的

import pandas as pdimport mysql.connectorfrom sqlalchemy import create_engineengine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)cnx = engine.raw_connection()data = pd.read_sql('SELECT * FROM sample_table', cnx)

感觉这么写更加正规一些,因为read_sql的反向操作to_sql只支持两类MySQL引擎,一个是sqlalchemy,另一个是sqlliet3

具体可以参考:
http://blog.csdn.net/qq_34685317/article/details/72896306

关于contextlib的介绍,和关于with结构的解析,参考:
https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/

to_sql这么写还是会报错
DatabaseError: Execution failed on sql ‘SELECT name FROM sqlite_master WHERE type=’table’ AND name=?;’: not all arguments converted during string formatting

还在寻求解决办法中。。。。。。。。。。

原创粉丝点击