gpt4 book ai didi

Python .format 在使用 psycopg2 时向字符串添加额外的引号

转载 作者:行者123 更新时间:2023-11-29 13:15:29 27 4
gpt4 key购买 nike

<分区>

希望有人能帮助我,因为我在这里陷入困境。

尝试使用 python、psycopg2 和 postgresql 复制表格并将其输出为 CSV。我需要将表名和输出文件名作为变量,因为稍后我会将表名更改为数组,以便它可以遍历多个表。

我的代码在下面,但我不断收到以下错误,似乎添加了一组额外的引号。请问有人知道如何解决这个问题吗?

fullTempBaseURL 是:C:\Administrator Files\Worksorders.csv

fullRawCSVURL 是:G:\Team Drives\RawCSV\Worksorders.csv

“C:\Administrator Files\Worksorders.csv”处或附近的语法错误第 1 行:复制 (SELECT * FROM "Worksorders") 到 "C:\Administrator Fil...

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()

提前致谢,乔恩

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com