【问题标题】:syntax error at or near "(" postgresql + Python“(”处或附近的语法错误 postgresql + Python
【发布时间】:2018-06-07 19:02:50
【问题描述】:

我正在使用 Jupyter 笔记本来处理一些带有 postgresql 的数据库 我有以下情况:

import pandas as pd
import (other packages)
conn_string= % I can't show this, but this is ok
conn = psycopg2.connect(conn_string)
cursor=conn.cursor
query= """ copy (select col1,col2 from Table where col3=a_parameter
           and col4=b_parameter) to '/tmp/test.csv' with csv """
pd.read_sql(query,conn)

但是我收到了这个错误:

**ProgrammingError: syntax error at or near "("
LINE 1: COPY (select col1,col2 from Table where col3...**
             ^

为什么复制句子有错误? 我使用的是 Postresql 8.0.2

【问题讨论】:

  • 您的旧版本did not support COPY 命令中的选择语句。 如果您使用的是过时版本,您还应该阅读该版本的手册,而不是较新版本的手册。您应该现在升级到受支持和维护的版本。
  • 请升级您的 Postgres。我们现在有 10 个,距离第 8 版已经有很多年了。
  • 我正在使用 Jupyter Notebook + Python 3.4+ psycopg2(它允许我进行 postgresql 查询)。如何升级?有没有将数据导出到 csv 的选项?

标签: postgresql export-to-csv psycopg2 postgresql-8.0


【解决方案1】:

类似这样的:

import csv
            my_file_csv =  my_folder + "\Report_Trip_Day_" + my_opr + "_" + my_local_database + ".csv"


            out = csv.writer(open(my_file_csv, "w", newline=''), delimiter=',', quoting=csv.QUOTE_ALL)
            out.writerow(colnames)
            for row in my_xls_report_table:
                out.writerow(row)

【讨论】:

    【解决方案2】:

    你可以这样做:

    query= """ copy (select col1,col2 from Table where col3=a_parameter
           and col4=b_parameter) """
    
    df=pd.read_sql(query,con=conn)
    df.to_csv("name.csv",sep=",")
    

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 2016-11-22
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多