用Python操纵MySQL
本例用Python操纵MySQL,从指定文件读取数据,并对数据进行处理,处理之后批量插入MySQL。
贴上代码:
# -*- coding: gbk -*- import re
import MySQLdb
import time def select(sqlselect):
try:
conn = MySQLdb.connect("localhost","test","","testdb" )
cursor=conn.cursor()
# 使用execute方法执行SQL语句
cursor.execute(sqlselect)
# 使用 fetchone() 方法获取一条数据。
data = cursor.fetchone()
#读取所有行
data = cursor.fetchall()
return data
except Exception,e:
print e
#print "Data from mysql: %s %s %s %s" %(data[0],data[1],data[2],data[3])
finally:
# 关闭数据库连接
conn.close() def loadData(dataFile,rowlimts=0):
#dataFile=r'E:\cabspottingdata\new_abboip.txt'
cabid=dataFile[dataFile.index('_')+1:dataFile.index('.')]
myFile=open(dataFile,'r',2048)#2048为缓冲大小
newline=myFile.readline()
records=[]
splitter=re.compile('\\s')#以空白字符作为分隔符
rows=0
if rowlimts>0:
while newline and rows<rowlimts:
content=splitter.split(newline)
record=[]
record.append(float(content[0]))
record.append(float(content[1]))
record.append(int(content[2]))#int型也可插入到数据库的bit型字段 dt=time.gmtime(int(content[3]))#将unix时间,如1213084687,转换成time类型
dtStr=time.strftime('%Y-%m-%d %H:%M:%S',dt)#将time对象,格式化为"2008-06-10 07:58:07"型字符串
record.append(dtStr) record.append(cabid)
records.append(record)
rows+=1
newline=myFile.readline()
else:
while newline:
content=splitter.split(newline)
record=[]
record.append(float(content[0]))
record.append(float(content[1]))
record.append(int(content[2])) dt=time.gmtime(int(content[3]))
dtStr=time.strftime('%Y-%m-%d %H:%M:%S',dt)
record.append(dtStr) record.append(cabid)
records.append(record)
newline=myFile.readline()
myFile.close()
return records def insertItems(records):
if len(records)>0:
#注意,不论MySQL的表结构中,某个字段为何种类型,Python的SQL语句中都要用%s来表示格式
sql="insert into geoinfo(latitude,longitude,occupancy,time,cabid)values(%s,%s,%s,%s,%s)"
values=[]
for record in records:
values.append((record[0],record[1],record[2],record[3],record[4]))
try:
conn = MySQLdb.connect("localhost","test","","testdb" )
_cursor=conn.cursor()
#批量插入
_cursor.executemany(sql,values)
conn.commit()#Insert和update操作必须调用commit方法,操作才能生效
return 0
except Exception,e:
raise e
return -1
finally:
conn.close() def insertItem(record):
if record!=None:
#注意,不论MySQL的表结构中,某个字段为何种类型,Python的SQL语句中都要用%s来表示格式
sql="insert into geoinfo(latitude,longitude,occupancy,time,cabid)values(%s,%s,%s,%s,%s)"
sql=sql%(record[0],record[1],record[2],record[3],record[4])
try:
conn = MySQLdb.connect("localhost","test","","testdb" )
_cursor=conn.cursor()
_cursor.execute(sql)
conn.commit()
return 0
except Exception,e:
raise e
return -1
finally:
conn.close() if __name__=='__main__': dataFile=r'E:\cabspottingdata\new_abboip.txt'
records=loadData(dataFile)
print 'inserting %d records'%len(records)
insertItems(records)
data=select("select objectid from geoinfo limit 0,10")#查询前10条
print data
print 'inserting completed.'
注意事项:
1)批量插入时,cursor.execute()放在for循环中的执行,其效率远不如cursor.executemany()方法。
2)不论MySQL的表结构当中,某个字段为何种类型,如float,int,bit,datetime型, Python的SQL语句中都要用%s来表示格式,否则对于非字符串类型的字段,插入式可能会报错。
例如,我在插入geoinfo表(结构如下,objectid字段为自增长)时,当插入语句写成 sql="insert into geoinfo(latitude,longitude,occupancy,time,cabid)values(%f,%f,%d,%s,%s)" 时会报错:
"float argument required, not str"

后来改成 sql="insert into geoinfo(latitude,longitude,occupancy,time,cabid)values(%s,%s,%s,%s,%s)" 就没错了。
另外,对于37.75134和-122.39488这样的小数型,若字段设计为float型时,插入时,MySQL会自动将其截断,并作四舍五入,
我以为是长度不够,于是改长度为50,插入时却被自动截断为整数,后改成double型才可以。
用Python操纵MySQL的更多相关文章
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
preface: 近期帮师兄处理json文件,须要读到数据库里面,以备其兴许从数据库读取数据.数据是关于yelp站点里面的: https://github.com/Yelp/dataset-examp ...
- 第二篇:操纵MySQL数据库(2) - 基于ORM思想的SQLAlchemy库
前言 本文讲解在Python语言中使用SQLAlchemy库操纵MySQL数据库的方法. 由于具体内容涉及较多,本文仅以插入及展示数据为例,更多内容请查阅有关文档. ORM ORM也即对象 - 关系映 ...
- 第一篇:操纵MySQL数据库(1) - 基于MySQLdb库
前言 本文讲解在Python语言中使用MySQLdb库操纵MySQL数据库的方法. 准备工作 1. 安装Python和MySQL2. 安装MySQLdb (exe下载地址:http://sourcef ...
- Python 3 mysql 库操作
Python 3 mysql 库操作 一.基础相关知识 MySQL数据库基本操作知识储备 数据库服务器:一台计算机(对内存要求比较高) 数据库管理系统:如mysql,是一个软件 数据库:oldboy_ ...
- python操作MySQL数据库的三个模块
python使用MySQL主要有两个模块,pymysql(MySQLdb)和SQLAchemy. pymysql(MySQLdb)为原生模块,直接执行sql语句,其中pymysql模块支持python ...
- 【初学python】使用python连接mysql数据查询结果并显示
因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...
- Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- 使用 python 管理 mysql 开发工具箱 - 1
Mysql 是一个比较优秀的开源的数据库,很多公司都在使用.作为运维人员,经常做着一些重复性的工作,比如创建数据库实例,数据库备份等,完全都可以使用 python 编写一个工具来实现. 一.模块 Co ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
随机推荐
- 软工实践练习——使用git进行代码管理心得
一.在Github上注册账户.其中创建organization在小组成员的账户上创建,并在其账户上创建了小组的版本库.在创建organization的过程中,参考了助教提供的博客:http://sef ...
- JS模式:又一个简单的工厂模式
<!DOCTYPE html> <html> <head> <title></title> </head> <body&g ...
- requirejs
//index.html <!doctype html> <html> <head> <meta charset="utf-8"> ...
- Java设计模式-迭代子模式(Iterator)
顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松.这句话包含两层意思:一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对 ...
- Oracle中的伪列
分页查询中,需要用到伪列rownum,代码如下: select * from (select rownum rn, name from cost where rownum <= 6) where ...
- python:open文件操作
file: jim|123|1 tom|321|3 kamil|432|1 # __author__ = liukun # coding:utf-8 obj = open('file.txt','r' ...
- 【bzoj1046】 HAOI2007—上升序列
http://www.lydsy.com/JudgeOnline/problem.php?id=1046 (题目链接) 题意 给出一个数列,求数列中长度为L的下标字典序最小的上升子序列. Soluti ...
- Python之MySQL
本文我们为大家介绍 Python3 使用 PyMySQL 连接数据库,并实现简单的增删改查. 什么是 PyMySQL? PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一 ...
- thinkphp ajax添加及删除
写在前面的话:应客户需求需要给后台增加自助添加电影名称和链接的功能,添加后在微信前台能自动读取显示.开发步骤:1.由于是给后台添加一个增加电影及电影链接的功能,所以控制器在Admin下.在路径 App ...
- linux mysql 相关操作命令
1.linux下启动mysql的命令:mysqladmin start/ect/init.d/mysql start (前面为mysql的安装路径) 2.linux下重启mysql的命令:mysqla ...