【问题标题】:Use of variables in postgres script在 postgres 脚本中使用变量
【发布时间】:2016-10-24 15:07:56
【问题描述】:

我想在我的 SQL 脚本中使用一个变量。变量的值为 100(只是一个数字)。我已将其存储为 csv。此目录中的文件:C:\Users\Dino\Desktop\my_file.csv。

我想在 sql 脚本中运行这个:

import os
from ask_db import ask_db_params #this script creates the connection to the  database
import sys, os
def my_function(cur, conn):
    sql="""
        \set outputdir'C:\\Users\\Dino\\Desktop'
        \set new_var :outputdir '\\my_file.csv'
         copy my_file to :'new_var';"""

cur.execute(sql)
conn.commit()
if __name__ == '__main__':
  try:
    conn = ask_db_params()
    cur  = conn.cursor()
    analysis_data(cur,conn)
    logging.info('Data analysed.')
  except Exception as e:
    logging.error('Failure', exc_info=True)
    exit(1)

我有错误:

“\”处或附近的语法错误 ....

它指的是第一行。

关于语法的任何帮助?

附:我正在运行 python 来调用 sql 脚本。视窗操作系统

【问题讨论】:

  • 您是否调用psql 来读取脚本?
  • 代码如下: def my_function(cur,conn): sql = """\set outputdir 'C:\\Users\\Dino\\Desktop' \set new_var :outputdir '\ \my_file.csv' 将 my_file 复制到 :'new_var'; """.
  • 更多,更多!请分享整个代码。编辑问题以执行此操作。
  • 我做到了。需要更多?
  • \set 是一个psql 命令。不能在psql之外使用

标签: python windows postgresql psql


【解决方案1】:

那行不通。 \setpsql 命令,而不是 SQL 命令。

您必须在 Python 中使用字符串操作来构造如下所示的 SQL 字符串:

COPY my_file TO 'C:\Users\Dino\Desktop\my_file.csv'

然后将execute() 与该 SQL 字符串一起使用。

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 2021-11-04
    • 1970-01-01
    • 2020-01-20
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2023-03-30
    相关资源
    最近更新 更多