本例用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的更多相关文章

  1. python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题

    preface: 近期帮师兄处理json文件,须要读到数据库里面,以备其兴许从数据库读取数据.数据是关于yelp站点里面的: https://github.com/Yelp/dataset-examp ...

  2. 第二篇:操纵MySQL数据库(2) - 基于ORM思想的SQLAlchemy库

    前言 本文讲解在Python语言中使用SQLAlchemy库操纵MySQL数据库的方法. 由于具体内容涉及较多,本文仅以插入及展示数据为例,更多内容请查阅有关文档. ORM ORM也即对象 - 关系映 ...

  3. 第一篇:操纵MySQL数据库(1) - 基于MySQLdb库

    前言 本文讲解在Python语言中使用MySQLdb库操纵MySQL数据库的方法. 准备工作 1. 安装Python和MySQL2. 安装MySQLdb (exe下载地址:http://sourcef ...

  4. Python 3 mysql 库操作

    Python 3 mysql 库操作 一.基础相关知识 MySQL数据库基本操作知识储备 数据库服务器:一台计算机(对内存要求比较高) 数据库管理系统:如mysql,是一个软件 数据库:oldboy_ ...

  5. python操作MySQL数据库的三个模块

    python使用MySQL主要有两个模块,pymysql(MySQLdb)和SQLAchemy. pymysql(MySQLdb)为原生模块,直接执行sql语句,其中pymysql模块支持python ...

  6. 【初学python】使用python连接mysql数据查询结果并显示

    因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...

  7. Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy

    本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...

  8. 使用 python 管理 mysql 开发工具箱 - 1

    Mysql 是一个比较优秀的开源的数据库,很多公司都在使用.作为运维人员,经常做着一些重复性的工作,比如创建数据库实例,数据库备份等,完全都可以使用 python 编写一个工具来实现. 一.模块 Co ...

  9. 练习:python 操作Mysql 实现登录验证 用户权限管理

    python 操作Mysql 实现登录验证 用户权限管理

随机推荐

  1. 每天一个linux命令(34):kill命令

    Linux 中的kill命令用来终止指定的进程(terminate a process)的运行,是Linux下进程管理的常用命令.通常,终止一个前台进程可以 使用Ctrl+C键,但是,对于一个后台进程 ...

  2. simple-LDAP-auth

    <?php /** * simple class for LDAP authentification * Copyright (C) 2013 Petr Palas This program i ...

  3. WebForm控件之DropDownList

    DropDwonList 三件事: ------------------------------------------1.把内容填进去-------------------------------- ...

  4. BIEE 后台新建分析没有你创建的数据源

    (1)登录http://win-5rnnibkasrt:9704/analytics/saw.dll?bieehome  点击“管理” 找到“发出SQL语句”在里面写call sapurgeallca ...

  5. 大数据测试之hadoop命令大全

    1.列出所有Hadoop Shell支持的命令 $ bin/hadoop fs -help2.显示关于某个命令的详细信息 $ bin/hadoop fs -help command-name3.用户可 ...

  6. iBatisnet系列(二) 配置运行环境和日志处理

    http://hjf1223.cnblogs.com/archive/2006/04/24/383119.aspx 刚爬完鼓山回来,想到这篇刚刚开始,不敢怠慢,洗完澡休息一下就到电脑旁边来了.现在我开 ...

  7. ExtJS入门教程03,form中怎能没有validation

    接上篇内容,我们在学会extjs form的基本用法之后,今天我们来看看extjs form的validation功能. 必填项,就是不能为空(allowBlank) 效果: 代码: { xtype: ...

  8. jquery------隐式迭代

    其中Jq方法遍历内部dom数组的过程就叫做[隐式迭代] my.js $(document).ready(function(){ (function($){ $.fn.swapClass=functio ...

  9. 在不借助其他工具的情况下破解Windows开机密码

    文章:http://www.cnblogs.com/vforbox/p/4828855.html#!comments. 从该文章我们也可以得到一个快速启动某个程序的方法:将自己常用的程序命名为seth ...

  10. latin1

    Latin1是ISO-8859-1的别名,有些环境下写作Latin-1.ISO-8859-1编码是单字节编码,向下兼容ASCII,其编码范围是0x00-0xFF,0x00-0x7F之间完全和ASCII ...