希望有人能帮我,因为我正忙得不可开交。在
尝试使用python、psycopg2和postgresql复制表并将其输出为CSV。我需要将表名和输出文件名作为变量,因为稍后我将把tablename更改为一个数组,这样它就可以遍历多个表。在
我的代码在下面,但我一直得到以下错误,似乎是添加了一套额外的引号。有人知道怎么避开这个麻烦吗?在
fullTempBaseURL为:C:\Administrator Files\工作订单.csv在
fullRawCSVURL是:G:\Team Drives\RawCSV\工作订单.csv在
“C:\Administrator Files”处或附近出现语法错误\工作订单.csv"" 第1行:复制(从“工作订单”中选择*到“C:\管理员文件。。。在
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()
先谢谢你,乔恩
文件名不应该是标识符,应该用单引号引起来。您可以使用
sql.Literal
。在相关问题 更多 >
编程相关推荐