gpt4 book ai didi

python - 如何在python中构建动态sql查询并使用executemany()插入?

转载 作者:行者123 更新时间:2023-11-29 22:06:55 24 4
gpt4 key购买 nike

在我的代码中,我从 MySQL 表中选择 10,000 行数据,并构建一个每次插入 100 行的列表。我正在将数据插入另一台服务器上的表中。我希望能够将此代码用于具有不同值和列的表。我怎样才能做到这一点?

这是我到目前为止的代码:

while outerIndex<outerLoops:

ts1 = time.time()
ts2 = 0

sqlReadRows = 'SELECT * FROM `user_session_0805` WHERE record_time >=%s AND record_time < %s ORDER BY record_time ASC LIMIT %s'
readCur.execute(sqlReadRows,(startTime, maxTime, selectLimit))

dataResults = readCur.fetchall()
innerLoops = len(dataResults)
innerIndex = 0

batch = []
while innerIndex<innerLoops:
if len(dataResults) <100:
for row in dataResults:
if row:
batch.append(
row
)
else:

for i in range(innerIndex, innerIndex+100):
if dataResults[i]:
batch.append(
dataResults
)
else:
break

innerIndex+=100

sqlWrite = # Generate sql

if batch:
writeCur.executemany(sqlWrite, batch)
cnx2.commit()
startTime = batch[-1][1]
ts2 = time.time()
print 'Took %s secs to insert %s rows of data'%(int(ts2-ts1), len(batch))

outerIndex+=1

我对 Python 还很陌生,所以我也很感激任何有用的建议!

最佳答案

您没有对数据进行任何修改,对吧?您可以将 SELECT 结果直接插入到新表中:

INSERT INTO newTable
SELECT
*
FROM `user_session_0805`
WHERE record_time >=%s
AND record_time < %s
ORDER BY record_time ASC
LIMIT %s

您不必先创建newTable,MySQL 会为您处理这个问题。但你应该做一个

DROP TABLE IF EXISTS newTable;

更新

您可以使用以下方法将值导出到 csv 文件

SELECT 
*
FROM `user_session_0805`
WHERE record_time >=%s
AND record_time < %s
ORDER BY record_time ASC
LIMIT %s
INTO OUTFILE 'c:/myFile.csv'

关于python - 如何在python中构建动态sql查询并使用executemany()插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32079510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com