有很多这样的例子,但在我看到的所有情况下,他们都知道字段(列)的名称。这两个表具有完全相同的列/字段。在
我的解决方案解决了我当前的问题,但正如你从代码中看到的,它可能有资格获得“年度最荒谬代码”奖。在# Copy data from one table to another in the same database
print '-' * 70
print 'Copy data from one table to another in the same database\n'
print ' Usefull for creating test data.'
print '-' * 70
import sqlite3
connection = sqlite3.connect("table.sqlite")
cursor = connection.cursor()
source_table = 'table1'
target_table = 'test_table1'
stmt = "SELECT * FROM %s" % source_table
cursor.execute(stmt)
data = cursor.fetchall()
for row in data:
stmt = "insert into %s values " % target_table + str(row)
stmt = stmt.replace("u'", '"')
stmt = stmt.replace("'", '"')
stmt = stmt.replace(' None', ' Null')
cursor.execute(stmt)
connection.commit()
connection.close()
必须有更好(更可靠)的方法来做到这一点。在
本文展示了如何使用Python的sqlite3库从一个表(source_table)复制所有数据到另一个表(target_table)。代码虽然实现了功能,但可能被评为‘年度最荒谬代码’,因为它涉及字符串格式化和替换操作来构建SQL插入语句,这可能不安全且效率低下。作者寻求更可靠和高效的方法。
5万+

被折叠的 条评论
为什么被折叠?



