Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—我可以使用另一个数据库中的游标(从select)将行插入到一个数据库中吗?_Python_Sql_Postgresql_Sqlite_Pyodbc - Fatal编程技术网

Python—我可以使用另一个数据库中的游标(从select)将行插入到一个数据库中吗?

Python—我可以使用另一个数据库中的游标(从select)将行插入到一个数据库中吗?,python,sql,postgresql,sqlite,pyodbc,Python,Sql,Postgresql,Sqlite,Pyodbc,我试图从我们的主数据库(postgres)中选择数据,并将其插入一个临时的sqlite数据库,以便进行一些比较、分析和报告。在Python中有没有一种简单的方法可以做到这一点?我正在尝试这样做: 从主Postgres数据库获取数据: import psycopg2 postgres_conn = psycopg2.connect(connection_string) from_cursor = postgres_conn.cursor() from_cursor.execute("SELECT

我试图从我们的主数据库(postgres)中选择数据,并将其插入一个临时的sqlite数据库,以便进行一些比较、分析和报告。在Python中有没有一种简单的方法可以做到这一点?我正在尝试这样做:

从主Postgres数据库获取数据:

import psycopg2
postgres_conn = psycopg2.connect(connection_string)
from_cursor = postgres_conn.cursor()
from_cursor.execute("SELECT email, firstname, lastname FROM schemaname.tablename")
插入到SQLite表中:

import sqlite3
sqlite_conn = sqlite3.connect(db_file)
to_cursor = sqlite_conn.cursor()
insert_query = "INSERT INTO sqlite_tablename (email, firstname, lastname) values %s"
to_cursor.some_insert_function(insert_query, from_cursor)
因此,问题是:是否有一个
某种插入函数
适用于此场景(使用pyodbc或使用sqlite3)

如果是,如何使用?上面的
insert\u查询是否有效?还是应该修改


如果Python中不存在这样的函数,我们也将非常感谢任何其他建议/方法。提前谢谢

您可以从pyodbc或sqlite查看executemany。如果可以从select生成参数列表,则可以将该列表传递给ExecuteMy


根据您计划插入的记录数量,性能可能是一个问题,如本期公开发行中所述

您应该将select查询的结果传递给
execute\u many

insert_query = "INSERT INTO smallUsers values (?,?,?)"
to_cursor.executemany(insert_query, from_cursor.fetchall())
还应使用参数化查询(?标记),如下所述:

如果要避免将整个源数据库加载到内存中,可以使用以下代码一次处理100行:

while True:
    current_data = from_cursor.fetchmany(100)
    if not current_data:
        break
    to_cursor.exectutemany(insert_query, current_data)
    sqlite_conn.commit()
sqlite_conn.commit()

更新信息:pyodbc的
fast\u executemany
属性我一直在寻找一种不使用
fetchall()
的方法,因为它可以根据数据的大小在内存中创建一个巨大的列表。您可以改为使用fetchmany(100)。您可以尝试以下操作:
while True:current\u data=from\u cursor.fetchmany(100)如果不是current\u data:break to\u cursor.executemany(插入\u查询,当前\u数据)