Python.format在使用psycopg2时向字符串添加额外引号
希望有人能帮助我,因为我在这里陷入困境 尝试使用python、psycopg2和postgresql复制表并将其输出为CSV。我需要将表名和输出文件名作为变量,因为我稍后会将表名更改为数组,以便它可以在多个表中循环 下面是我的代码,但我一直遇到以下错误,似乎添加了一组额外的引号。有人知道怎么绕过这个吗 fullTempBaseURL为:C:\Administrator Files\Worksorders.csv fullRawCSVURL为:G:\Team Drives\RawCSV\Worksorders.csv “C:\Administrator Files\Worksorders.csv”处或附近出现语法错误 第1行:复制(从“工作订单”中选择*到“C:\Administrator文件…”Python.format在使用psycopg2时向字符串添加额外引号,python,string,postgresql,psycopg2,Python,String,Postgresql,Psycopg2,希望有人能帮助我,因为我在这里陷入困境 尝试使用python、psycopg2和postgresql复制表并将其输出为CSV。我需要将表名和输出文件名作为变量,因为我稍后会将表名更改为数组,以便它可以在多个表中循环 下面是我的代码,但我一直遇到以下错误,似乎添加了一组额外的引号。有人知道怎么绕过这个吗 fullTempBaseURL为:C:\Administrator Files\Worksorders.csv fullRawCSVURL为:G:\Team Drives\RawCSV\Works
import psycopg2
from config import config
from psycopg2 import sql
import os
tablename = 'Worksorders'
tempBaseURL = 'C:\Administrator Files'
RawCSVBaseURL = 'G:\Team Drives\RawCSV'
fileType = '.csv'
global fullTempBaseURL
global fullRawCSVURL
fullTempBaseURL = tempBaseURL + '\\' + tablename + fileType
fullRawCSVURL = RawCSVBaseURL + '\\' + tablename + fileType
print "fullTempBaseURL is: " + fullTempBaseURL
print "fullRawCSVURL is: " + fullRawCSVURL
###########################
#Copy table to CSV
###########################
def tabletoCSV():
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the SQL statement
cur.execute("SET search_path TO dbo")
cur.execute(sql.SQL("""copy (SELECT * FROM {tbl} ) to {url} with csv""").format(tbl = sql.Identifier(tablename), url = sql.Identifier(fullTempBaseURL)))
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def moveFile():
os.rename(fullTempBaseURL, fullRawCSVURL)
tabletoCSV()
提前谢谢,Jon文件名不应该是标识符,应该用单引号引起来。你可以用
sql.Literal
来代替。有很多代码似乎与问题无关。做一个标记可能有助于得到答案。下次注意,但你能帮忙吗?很难看出是什么原因导致了问题re.我最好的猜测是,您可能已经引用了表样式的文件路径,而不是将其设置为字符串常量。虽然这与错误消息已经告诉您的内容非常接近,但我不确定这是否有帮助。我无法升级投票,因为我没有声誉,但非常感谢Piro!!