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
还在寻求解决办法中。。。。。。。。。。
- Pandas中用with结构与MySQL数据库交互
- pandas和数据库进行交互(以mysql为例)
- 图片与mysql数据库的交互
- android 做登陆与mysql数据库交互
- python实现与mysql数据库交互
- Mysql数据库简介以及Mysql与python3的交互
- MySQL导出数据库结构与备份
- Flash8与PHP-MySQL数据库间的交互
- 基于MySQL数据库的C#与Python语言交互调用
- Python3.4借助PyMySQL与MySQL数据库的基本交互
- NHibernate与MySQL数据库交互(类和表的映射)
- xml与数据库交互
- flex与数据库交互
- flex与数据库交互
- flex与数据库交互
- ajax与数据库交互
- MySql中用命令行复制表结构
- mysql中用命令行复制表结构
- Unity内存优化技术测试案例
- 遍历 Map的方法
- 泛型-上下限
- linux文本操作命令整理
- Linux基础-特殊权限
- Pandas中用with结构与MySQL数据库交互
- golang mongodb upsert
- Web访问控制
- 转换到 COFF 期间失败: 文件无效或损坏
- String类引用计数的写时拷贝
- Type-C离一统江山只差一个液态金属?
- 聊聊iOS开发中的单元测试
- awvs11批量脚本
- 一个Java在线预览和下载的例子