【Python】python读取文件操作mysql

尾大不掉,前阵子做检索测试时,总是因为需要业务端操作db和一些其他服务,这就使得检索测试对环境和数据依赖性特别高,极大提高了测试成本。

Mock服务和mysql可以很好的解决这个问题,所以那阵子做了两个工作:

1 使用公司的service框架Mock服务;

2 使用python语言Mock mysql数据。

部分1只需要了解公司框架即可进行编写,本文主要记录下python操作mysql的部分。

一 安装环境

安装python即需要的MySQLdb模块(yum install MySQL-python.x86_64),如下,安装成功。

[[email protected]118-69 ~]# python
Python 2.6.6 (r266:84292, Feb 22 2013, 00:00:18)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> 

二 实现python操作数据库

1 我第一次实现的是读取文件操作数据库(注释掉的为自增键处理)如下:

#-*- coding:utf-8 -*-
import MySQLdb
from itertools import islice
try:
    conn = MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,port=3306,charset=‘utf8‘)#连接mysqldb
    cur = conn.cursor()
    conn.select_db(‘test‘)
#    cur.execute(‘select max(id) from student‘)#获取mysql中该表的自增键最大值,向后添加。
#    maxid = cur.fetchall()[0]
#    print ‘maxid%id‘%maxid
#    start = count+1
    f = file(‘data2.txt‘)
    list = []
    line_num = 1
    for line in islice(f,1,None):#读取txt文件,跳过标题行
        strs = line.split(",")   #文件各字段逗号分隔
        line_num = line_num+1
        print len(strs)
        if len(strs)!=25:        #缺少字段时,跳过该行
            print ‘%d 行缺少字段,请检查文件‘%line_num
            continue
        data = (strs[0],strs[1],strs[2],strs[3],strs[4],strs[5],strs[6],strs[7],strs[8],strs[9],strs[10],strs[11],strs[12],strs[13],strs[14],strs[15],strs[16],strs[17],strs[18],strs[19],strs[20],strs[21],strs[22],strs[23],strs[24].replace("\n",""))   #对strs[24]空格进行处理
        print data
#    start = start+1
        list.append(data)        #将data记录到list中,对list执行插入操作
    f.close
    cur.executemany(‘insert into creative_info_test values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)‘,list)
    conn.commit()                #提交
    cur.close()
    conn.close()
    print ‘OK‘
except MySQLdb.Error,e:
    print "MySQL Error %d:%s"%(e.args[0],e.args[1])

2 领导说每条记录字段太多了(多表多字段),让我固定到脚本里,再单独更改,于是对第一版进行了修改,使用了字典dict:

#-*- coding:utf-8 -*-
import MySQLdb
conn = MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,port=3306,charset=‘utf8‘)#连接mysqldb
cur = conn.cursor()
conn.select_db(‘test‘)#逻辑:一次操作只为一次测试使用,所以第一步清除记录;第二步根据条数插入数据;第三个对插入数据进行个性化设置(部分字段的更新)。try:
        Delete()#数据清除
        Producer()#将默认数据插入mysql,注意自增主键
        Update()#个性化数据更新
        conn.commit()#提交
        cur.close()
        conn.close()
except MySQLdb.Error,e:
        print ‘MySQL Error %d,%s‘%(e.args[0],e.args[1])
#具体实现:插入数据,由于多表插入,切表与表之间有相同字段,所以根据条数做统一设置。
def Producer():
    print ‘input numbers :‘
    num = input()#请多写一条
    for i in range(1,num):
        table1[‘user_id‘]=i
        table2[‘user_id‘]=i...
        #insert table1
        user_info = [user[‘user_id‘]...]
        cur.execute(‘insert into user_test values(%s,...)‘,table1)
        #insert table2
        ...以下类似处理

def Update():
  print ‘input your sql语句 file name:‘
  filename = raw_input()
  f=file(filename)
  for line in f.readlines():
    operator your sql update  #写update语句即可
def Delete():
    cur.execute(‘delete from table1‘)
    cur.execute(‘delete from table2‘)  ...
#每个表对应一个dict,其字段为字典元素,为各字段设置默认值
table1={
‘user_id‘:‘5185173207809‘,
‘user_name‘:...,
}
table2={
...
}

三 附excel文件的读取,嗯,顺便感慨,python真棒:

import csv
f = open(‘creative_info_test.csv‘,‘rb‘)
reader = csv.reader(f)
for row in reader:
        print row
f.close
时间: 2024-08-08 12:25:21

【Python】python读取文件操作mysql的相关文章

Python学习之--文件操作

Python中对文件操作可以用内置的open()函数 读文件 f=open('/home/test/test.txt','r') # 读模式打开文件 f.read() # 读取文件内容 除了正常的读取文件内容,一个常用的操作是判断文件内容是否为空,如下: if len(f.read())==0: # 如果文件内容为空 xxxx 判断一个文件或者路径是否存在,如下(这里需要在代码中导入os module: import os): file='/home/test/test.txt' dir='/h

python解析xml文件操作的例子

python解析xml文件操作实例,操作XML文件的常见技巧. xml文件内容: <?xml version="1.0" ?> <!--Simple xml document__chapter 8--> <book> <title> sample xml thing </title> <author> <name> <first> ma </first> <last>

Python逐行读取文件内容

Python逐行读取文件内容thefile= open("foo.txt") line = thefile.readline() while line: print line, line = thefile.readline() thefile.close() Windows下文件路径的写法:E:/codes/tions.txt 写文件:thefile= open("foo.txt", "rw+")for item in thelist: the

python逐行读取文件脚本

逐行读取的方法很多,这里提供一种非常简单的方法: #!/usr/bin/python # -*- coding: utf-8 -*- for line in open("awip.conf"): print line 其他的可以参考教程:python逐行读取文件内容的三种方法Python--文件读取 原文地址:http://blog.51cto.com/weiruoyu/2140927

python 逐行读取文件的几种方法

Python四种逐行读取文件内容的方法 下面四种Python逐行读取文件内容的方法, 分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可. 方法一:readline函数 # -*- coding: UTF-8 -*- f = open("/pythontab/code.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: # pri

c++读取文件操作之peek、&gt;&gt;和get

预备知识: fstream提供了三个类,用来实现c++对文件的操作.(文件的创建.读.写). ifstream -- 从已有的文件读 ofstream -- 向文件写内容 fstream -- 打开文件供读写 文件打开模式: ios::in 读 ios::out 写 ios::app 从文件末尾开始写 ios::binary 二进制模式 ios::nocreate 打开一个文件时,如果文件不存在,不创建文件. ios::noreplace 打开一个文件时,如果文件不存在,创建该文件 ios::t

hadoop 读取文件操作

Path hdfsPath = new Path(args[0]); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(hdfsPath.toUri(),conf); CompressionCodecFactory factory = new CompressionCodecFactory(conf); CompressionCodec codec = factory.getCodec(hdfsPat

三:python数据类型和文件操作

一:字符串操作 1.字符串是可以通过下标来进行取值的,但是由于字符串是不可变变量,不能通过下标来修改它的值 username = 'li' username[0] 2.python里面的for循环,每次循环的时候,循环的是循环对象里面的每一个元素 3.len(names)#取变量的长度 4.#!/usr/bin/python #python里面有个这个话,代表在linux下运行的时候,去哪个目录下找python的解释器,在windows上运行不用写 5.# coding:utf-8 # __*_

python 从csv文件插入mysql数据库

一个工作遇到的问题,将excel文件的内容插入到mysql数据库中. 总体思路是 excel文件-->转换成csv文件-->csv文件读取-->读取数据插入mysql数据库 用到python的两个库csv和MySQLdb 下面是具体的code: 代码中数据库部分没啥好记录的,特别记录一下csv库的用法: # Insert data from csv file.csv_file = file('3D_PTlabs.csv', 'rb')csv_reader = csv.reader(csv