简体   繁体   English

在 python postgresql 中的参数化插入查询中出现语法错误

[英]Getting Syntax error in parametrize insert query in python postgresql

I am trying to send data to PostgreSQL, data is a tuple of strings ie (time, price).我正在尝试将数据发送到 PostgreSQL,数据是字符串元组,即(时间、价格)。

The problem is when I send data using a simple query ( not parametrized ) it works fine.问题是当我使用简单查询(未参数化)发送数据时,它工作正常。 Following is the simple query working perfectly.以下是完美运行的简单查询。

cur.execute("INSERT INTO paxos (date,price) VALUES ('2020-04-09 14:39:58.145804', '$1,664.08');");

But as those values aren't fixed, so I want to store them in variable and use a parameterized query for sending data, but the parameterized query isn't working for me.但是由于这些值不是固定的,所以我想将它们存储在变量中并使用参数化查询来发送数据,但是参数化查询对我不起作用。 Here is the parameterized query.这是参数化查询。

cur.execute("INSERT INTO paxos (date, price) values (?, ?)",(time, price))

Here is the complete function I am trying to implement:这是我正在尝试实现的完整 function:

def insert_data(time, price):

con = psycopg2.connect(database="", user="", password="", host="", port="5432")
print("Database opened successfully")
cur = con.cursor()

data_tuple = (time, price)

cur.execute("insert into paxos (date, price) values (?, ?)",(time, price))

con.commit()
print("Record inserted successfully")
con.close()
insert_data("2020-04-09 14:39:58.145804", "$1,664.08")

Here is the error message:这是错误消息:
图片链接

It seems like this is a python syntax error.看起来这是一个 python 语法错误。 I think you should use the format method of the string object (see codesnippet below).我认为您应该使用字符串 object 的格式方法(参见下面的代码片段)。 I can't test it right now, but according to some old code of mine, I always "built" a query string first and then passed the string object to the cursor.我现在无法测试它,但根据我的一些旧代码,我总是先“构建”一个查询字符串,然后将字符串 object 传递给 cursor。 Try something like that:尝试这样的事情:

artist = "Aphex Twin"
title = "Windowlicker"    
query = '''SELECT EXISTS(SELECT * FROM tracks
                    WHERE artist ILIKE \'{}\'AND
                    title ILIKE \'{}\')'''.format(artist, title)
cursor.execute(query)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM