gpt4 book ai didi

python - 将 Python 列表格式化为 SQL 脚本?

转载 作者:行者123 更新时间:2023-12-01 06:18:43 24 4
gpt4 key购买 nike

我有一个列表需要将其格式化为 SQL 脚本

list = 
[['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0\n'],
['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],
['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],

像这样的sql脚本:

INSERT INTO `Tbl_ABC` VALUES (11, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (12, 0, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (13, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)

这个我已经尝试过了

import pickle
import re
#RX = re.compile(r'^.*?\(\d+,\s0,.*\s0\)\s*$')

outfile = open('destination.sql', 'wb')
data = []
for ln in open('source.sql', 'r').xreadlines():
replace1 = ln.replace("INSERT INTO `Tbl_ABC` VALUES (", "")
replace2 = replace1.replace(")", "")
list_replace = replace2.split(',')
data.append(list_replace)
destinationdata = [d for d in data if d[1] == ' 0' and d[6]==' 0\n']#print '%s ,%s' % (list_replace[1], list_replace[6])

#start write line to destination.sql
#if RX.match(ln):

pickle.dump(destinationdata, outfile)
outfile.close()

感谢您的帮助!

最佳答案

Iterate over each element in the list
Unpack the element (which is also a list) into its fields
Generate a SQL line from these fields

完成工作的最简单和最丑陋的方法是:

list = [
['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0'],
['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0'],
['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0']]

for elem in list:
print 'INSERT INTO \'Tbl_ABS\' VALUES (%s, %s, %s, %s, %s, %s, %s)' % tuple(elem)

注意,我清除了 0 之后的“\n”(如果需要,请进行相应调整)。这对于一次性脚本来说是可以的。对于更严格的报告和转换,请查看一些模板库来分离数据和演示文稿。

关于python - 将 Python 列表格式化为 SQL 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817886/

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