我正在尝试使用从
创建的表在我的postgresql数据库中插入一行 CREATE TABLE public.coinbase_btc_usd
(
id bigserial primary key,
price integer NOT NULL,
buy integer NOT NULL,
sell integer NOT NULL,
"timestamp" timestamp with time zone
)
然而,当我的python 3.6脚本运行并尝试使用像这样的psycopg2添加一行时,它会返回一个错误,说明"没有结果可以获取"没有任何东西被添加到我的数据库中。
sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
" VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"
print(sql_query)
cur.execute(sql_query)
我还打印了sql_query变量,以确切了解尝试执行的内容并将其打印到输出
INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (16392.10, 16563.40, 16235.42, '2015-10-10 06:44:33.8672177')
答案 0 :(得分:1)
确保您提交交易:
cur.execute(sql_query)
conn.commit()
或者您可以启用自动提交以在执行后立即提交每个查询:
conn.autocommit = True
此外,防止SQL注入攻击无需任何成本 - 只需使用参数化查询。事实上,您的代码实际上更干净,更安全:
sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)"
cur.execute(sql_query, (exchange_rate, buy_rate, sell_rate, timestamp))
conn.commit()
答案 1 :(得分:0)
更改
sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
" VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"
为:
sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
" VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\') returning *"
这应该在我的假设中修复no results to fetch
。
如果您没有看到添加行,则很可能是begin
事务,并且从不提交它。