python & pandas链接mysql数据库
2016-06-08 09:44
375 查看
Python&pandas与mysql连接
1、python 与mysql 连接及操作,直接上代码,简单直接高效:
import MySQLdb try: conn = MySQLdb.connect(host='localhost',user='root',passwd='×××××',db='test',charset='utf8') cur = conn.cursor() cur.execute('create table user(id int,name varchar(20))' ) value = [1,'jkmiao'] cur.execute("insert into user values(%s,%s)",value) users = [] for i in range(20): users.append((i,"user"+str(i))) cur.executemany("insert into user values(%s,%s)",users) cur.execute("update user set name="test" where id=2") res = cur.fetchone() print res res = cur.fetchmany(10) print res print cur.fetchall() conn.commit() cur.close() conn.close() cur.execute('select * from user') cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
2、pandas 连接操作mysql:
import pandas as pd import MySQLdb conn = MySQLdb.connect(host="localhot",user="root",passwd="*****",db="test",charset="utf8") # read sql = "select * from user limit 3" df = pd.read_sql(sql,conn,index_col="id") print df # write cur = conn.cursor() cur.execute("drop table if exists user") cur.execute('create table user(id int,name varchar(20))' ) pd.io.sql.write_frame(df,"user",conn)
相关文章推荐
- 利用python进行数据分析-pandas入门2
- python安装ez_setup.py 【windows环境】
- Python while 循环使用实例
- Python数据类型转换
- python中的for循环如何控制步长
- python计算文件的行数和读取指定行的内容
- "Python" + "OpenCV" 环境配置
- python sqlalchemy 写数据
- [转]LIBSVM-3.18在python环境下的使用
- windows安装theano
- machine learning in action 之二 —— k-Nearest Neighbors
- Python入门笔记
- windows下python 安装igraph库报错 Cannot find the C core of igraph on this system using pkg-config.的解决
- python 列表解析
- python 多个迭代器 VS 单个迭代器
- python3.x dict 迭代
- Python3学习笔记02-程序文件改为脚本执行
- 廖雪锋笔记1---python变量类型
- python自学笔记
- panda3D学习之路