0

有很多这样的例子,但在我看到的所有情况下,他们都知道字段(列)的名称。这两个表具有完全相同的列/字段。

我的解决方案解决了我当前的问题,但正如您从代码中看到的那样,它可能有资格获得“年度最荒谬代码”奖。

# 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()

必须有更好(更可靠)的方法来做到这一点。

4

1 回答 1

1

使用cursor.executemany

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()

fields = ','.join('?' for desc in cursor.description)
stmt = "insert into {} values ({})".format(target_table, fields)
cursor.executemany(stmt, data)
connection.commit()
connection.close()

用于cursor.description获取列数据。

笔记

参数标记因数据库模块而异。sqlite3模块使用 qmark( ?)。如果您使用另一个数据库模块,您应该检查它。

于 2013-09-29T08:18:51.080 回答