【发布时间】:2018-10-22 14:51:07
【问题描述】:
我试图从 MSSQL 数据库中的一个表中选择一个到 PostgreSQL 数据库中的另一个表中。我很久以前读过“The_Fox”的这篇文章,试图做同样的事情:
copy data from MSSQL database to Postgresql database with Python
我的代码以此为基础,我设法通过“fetchone”从 MSSQL 一次获取一行到 postgresql,但是我没有设法“fetchall”并将一整列数据插入 postgresql。
使用以下代码,我得到了错误: “ProgrammingError:“[”处或附近的语法错误 第 1 行:插入 test_tabell VALUES ([])"
我的代码如下,有什么建议吗?
谢谢!
import pymssql, psycopg2
#Connect to the database
class DatabaseRequest:
def __init__(self):
self.conn1 = pymssql.connect(
host=r'*****',
user=r'*****',
password='*****',
database='*****'
)
self.conn2 = psycopg2.connect(host='*****', dbname='*****', user= '*****', password='*****')
self.cur1 = self.conn1.cursor()
self.cur2 = self.conn2.cursor()
# Fetch data from the MSSQL-database
def request_proc(self):
self.cur1.execute("SELECT table.column FROM table")
global rows
rows = self.cur1.fetchall()
# This prints all the information I want in my new table, so it seems to be able to fetch it, however in the form of "<class 'tuple'>"
for row in rows:
print(row)
print (type(row))
return rows
# Insert all data to an existing table in the postgresql database:
def insert_proc(self):
#This is the statement I think there is something wrong with:
self.cur2.execute("INSERT INTO table VALUES (%s)" % self.cur1.fetchall())
self.conn2.commit()
a = DatabaseRequest()
print(a.request_proc(), a.insert_proc())
【问题讨论】:
-
您确实有语法错误。您需要将
VALUES ([])切换为VALUES (val1, val2), (val3, val4)。在how to insert multiple rows on a single insert sql query 上阅读此主题 -
我的问题是:你为什么要使用 python 来做到这一点(而不是像 SSIS 这样或多或少的专用工具)?
标签: python sql-server postgresql