2016-02-04 65 views
0

我一直在試圖弄清楚如何在早上的大部分時間格式化一個COPY FROM SQL語句,我需要幫助。PostgreSQL:從SQL複製到特定列

我想從一個ASCII文本文件導入到我的Postgres數據庫中的表中的數據。我想它不喜歡我如何指定輸入ASCII文件。我已經試用過的文件路徑,沒有運氣:

file = os.path.normpath(os.path.join('c:\\','Users','dan','Desktop','New_Folder','Sept_2014','R01761','R01761_tex.asc')) 
file = r'C:\Users\dan\Desktop\New_folder\Sept_2014\R01761\R01761_tex.asc' 

這裏是我的腳本,我使用訪問我的數據庫:當我通過我的腳本在Python控制檯步驟

import psycopg2 

try: 
    conn = psycopg2.connect("dbname='reach_4a' user='root' host='localhost' port='9000' password='myPassword'") 
    tblname = "sept_2014"" 
    file = r"C:\Users\dan\Desktop\New_folder\Sept_2014\R01761\R01761_tex.asc" 
    #file = os.path.normpath(os.path.join('c:\\','Users','dan','Desktop','New_Folder','Sept_2014','R01761','R01761_tex.asc')) 
    cur = conn.cursor() 
    sql = "COPY %s (easting,northing,texture) FROM %s DELIMITERS ' ';" % (tblname,file) 
    cur.execute(sql) 
    conn.commit() 
except: 
    print "I am unable to connect to the database" 

#Close Database 
try: 
    conn.close() 
    print 'Database connection destroyed' 
except: 
    print "I cant close the database" 

,我得到以下錯誤,當我嘗試和運行cur.execute(sql)行:

--------------------------------------------------------------------------- 
ProgrammingError       Traceback (most recent call last) 
<ipython-input-34-c26e11f8fb81> in <module>() 
----> 1 cur.execute(sql) 

ProgrammingError: syntax error at or near "c" 
LINE 1: COPY sept_2014 (easting,northing,texture) FROM c:\Users\dan\... 
                ^

我是否正確取代我的琴絃到我的SQL語句?

回答

2

你應該把路分成報價

"COPY %s (easting,northing,texture) FROM '%s' DELIMITERS ' ';" 

我也想用的文件路徑參數化查詢:

sql = "COPY {field} (easting,northing,texture) FROM %s DELIMITERS ' ';".format(field=tblname) 
cur.execute(sql, (file,)) 

注意,在這種情況下,數據庫驅動程序將負責將引號放在字符串值附近。而且,作爲獎勵,你現在正在阻止SQL injection attacks

請注意,我們必須通過字符串格式將字段插入到查詢中。確保你知道tblname來自哪裏,你可以信任源,或者在查詢中使用之前驗證/清除/清理它。

+0

當我嘗試使用文件路徑方法實現參數化查詢時,出現以下錯誤:'psycopg2.OperationalError:無法打開文件「C:\ Users \ dan \ Desktop \ New_folder \ Sept_2014 \ R01761 \ R01761_tex。 asc「閱讀:沒有這樣的文件或目錄。但'os.path.isfile(file)'返回true。 – dubbbdan

+0

@dubbbdan那麼,你是否得到了同樣的錯誤,如果你只是圍繞佔位符(答案中的第一個建議)引號?謝謝。 – alecxe

+0

是的,我收到了同樣的錯誤。 – dubbbdan