Python从数据库读取大量数据批量写入文件

使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将数据加载进内存,这时我们需要将数据进行预处理,分批次加载进内存。下面是代码作用是将数据从数据库读取出来分批次写入txt文本文件,方便我们做数据的预处理和训练机器学习模型。

#%%
import pymssql as MySQLdb  #这里是python3  如果你是python2.x的话,import MySQLdb
#数据库连接属性
hst = '188.10.34.18'
usr = 'sa'
passwd = 'p@ssw0rd'
db = 'HistoryTrace'

#总共多少数据
allData = 1674333
#每个批次多少条数据
dataOfEach = 20000
#批次
batch = ceil(allData/dataOfEach)

#文件名
global IDctrl 
IDctrl = 1
filename = str(IDctrl)+'.txt'

#连接数据库
conn = MySQLdb.connect(host=hst,user=usr,password=passwd,database=db)
cur=conn.cursor()

while IDctrl<batch:
    #读取数据库
    sql = 'SELECT Longitude,Latitude,Altitude,VelComOfLong,VelComOfLati,Aircraft,Section,TimeMinus\
                FROM dealed1 where ID>=' + str(IDctrl) + ' and ID <' + str(IDctrl + dataOfEach) 
    cur.execute(sql)
    rows=cur.fetchall()
    #写文件
    f = open(filename,'w')
    f.writelines(str(rows))
    #文件名加1
    IDctrl+=1
    filename = str(IDctrl)+'.txt'
    
#关闭数据库连接
f.close()
conn.close()




猜你喜欢

转载自blog.csdn.net/tan_handsome/article/details/79261413
今日推荐