在 postgres 脚本中使用变量
Use of variables in postgres script
我想在我的 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)
我有错误:
syntax error at or near "\" ....
指的是第一行。
关于语法的任何帮助?
P.S。我正在 运行ning python 调用 sql 脚本。 WindowsOS
那不行。 \set
是 psql
命令,而不是 SQL 命令。
您将不得不在 Python 中使用字符串操作来构造一个 SQL 字符串,如下所示:
COPY my_file TO 'C:\Users\Dino\Desktop\my_file.csv'
然后将 execute()
与 SQL 字符串一起使用。
我想在我的 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)
我有错误:
syntax error at or near "\" ....
指的是第一行。
关于语法的任何帮助?
P.S。我正在 运行ning python 调用 sql 脚本。 WindowsOS
那不行。 \set
是 psql
命令,而不是 SQL 命令。
您将不得不在 Python 中使用字符串操作来构造一个 SQL 字符串,如下所示:
COPY my_file TO 'C:\Users\Dino\Desktop\my_file.csv'
然后将 execute()
与 SQL 字符串一起使用。