0

我在 MySQL 表中有数据,我想将其复制到 PostgreSQL 表中。一切正常,除非 MySQL 包含带有"和/或的字符串'

例如: MySQL 中的数据:

在此处输入图像描述

当我运行我的代码时,我得到:

ProgrammingError: ERROR:  syntax error at or near "t"

(不能的 t)

这是我的代码:

postgre = pg.connect(dbname=DB,user=USR,passwd=PASSWD,host=HOST, port=PORT)
crs = db_remote.cursor(MySQLdb.cursors.DictCursor)
crs.execute ("""select post_id, post_excerpt from tabl""")
data = crs.fetchall ()
for row in data :  
    postgre.query("""INSERT INTO importfrommysql(id,message)
    VALUES ('%s','%s')"""%(row["post_id"],row["post_excerpt"]))

连接pg.connect来自PygreSQL包装。我能做些什么?是否可以按原样获取文本?或者唯一的解决方案是在插入之前删除所有"/ '

4

1 回答 1

1

使用Psycopg cursor.execute参数传递:

import psycopg2
conn = psycopg2.connect(database='DB')
cursor = conn.cursor()

for row in data :

    cursor.execute ("""
        INSERT INTO importfrommysql (id,message)
        VALUES (%s,%s)
        """,
        (row["post_id"],row["post_excerpt"])
    )

它会根据需要转义和引用。

于 2016-11-07T10:41:56.723 回答