Python從資料庫讀取大量資料批量寫入檔案的方法

2022-10-04 18:39:10 字數 1051 閱讀 1458

使用機器學習訓練資料時,如果資料量較大可能我們不能夠一次性將資料載入進記憶體,這時我們需要將資料進行預處理,分批次載入進記憶體。

下面是**作用是將資料從資料庫讀取出來分批次寫入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 = www.cppcns.comceil(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 idctrlwww.cppcns.com #讀取資料庫

sql = 'select longitude,latitude,altitude,velcomoflong,velcomoflati,aircraft,section,timeminus\

from dealed1 where id>=' + str(idctrl) + ' and id

#檔名加1

idctrl+=1

filename = str(idctrl)+'.txt'

#關閉資料庫連線

f.close()

conn.close()

本文標題: python從資料庫讀取大量資料批量寫入檔案的方法

本文位址:

AppSettings從資料庫讀取

1 2 提供對配置資訊的訪問 3 4public static class520 2122 23 24 25 26static 27 37return38 3940 41 在啟動時以後台任務重新整理配置資訊 42 43static 4462 catch exception ex 6365 66 ta...

python連線MySQL資料庫並讀取資料

匯入模組 import pymysql 1.連線到mysql資料庫 conn pymysql.connect host localhost user root password 1234 db mycommodity charset utf8 localhost連線本地資料庫 user 使用者名稱 ...

python 連線 mysql 資料庫並讀取資料

注 mysqldb只支援python2,pymysql支援python3 注 pymysql.connect引數中的 host 伺服器位址,本機可用 localhost 2 使用cursor讀取資料 注 read sql cursor游標區別 read sql 只能執行查詢資料 cursor游標 可...