【问题标题】:Copy a whole table from MSSQL to PostgreSQL with Python code使用 Python 代码将整个表从 MSSQL 复制到 PostgreSQL
【发布时间】: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


【解决方案1】:

你实际上并不需要 python。

您可以将表从 SQL Server 导出为 .txt 或 .csv,然后将其导入 PostgreSQL,但可能存在一些格式问题。 确保您的列等名称相同。

这种方式应该比 Python 更容易。

祝你好运! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2012-09-14
    • 2019-08-14
    相关资源
    最近更新 更多