psycopg2程序错误:选择附近的语法错误

2024-04-19 15:01:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,它读取一个sql文件并执行其中存储的sql命令。但在执行时,我遇到了以下错误:

psycopg2.ProgrammingError: syntax error at or near "select"
LINE 1: select * from image

sql文件内容为:

select * from image

这很简单,应该是正确的。在

引发错误的代码(最后一行,更具体地说):

^{pr2}$

有人能给我建议吗?在

----更新-----

下面是python脚本中的函数。因为剧本太长了,所以我不把它贴出来。在

def list_(csv, sql=None , script=None , host = None, dbname=None , user=None , pwd=None):
    print(sql)
    print(script)
    if (sql):
        print("sql")
        with conn2db(host,dbname,user,pwd) as conn:
            cur = conn.cursor()
            cur.execute(sql)
    if (script):
        print("script")
        with conn2db(host,dbname, user, pwd) as conn:
            cur = conn.cursor()
            string =  open(script, 'r', encoding='utf-8').read()
            print(string)
            cur.execute(string)
            #cur.execute(open(script, 'r', encoding='utf-8').read())
    with open(csv,'w') as file:
        for record in cur:
            mystr=str(record)[1:-2] if str(record)[-1]==',' else str(record)[1:-1]
            file.write(mystr+'\n')
            #file.write('\n')

Tags: nonehostsqlifaswithpwdscript
2条回答

在数据库中查看连接字符串以及模式和表会有所帮助。请确认这些都是正确的。另外,在从文件中读取SQL字符串或在SQL字符串末尾添加分号后对其运行.strip()值得一试。在

今天我又碰到了这个问题,我删除了原始文件,创建了一个新文件,并输入了sql命令。现在一切都很有魅力。在

我的猜测是,原始文件包含一些不可见的字符,导致了这个问题。但他们为什么会在那里存在,我仍然困惑不解。在

相关问题 更多 >