【发布时间】:2021-03-29 21:51:28
【问题描述】:
我正在编写一个跟踪股票价格的程序。我正在尝试执行 INSERT 查询,它执行了,但什么也没做。
这是我的类 SQLDatabaseOperator 中的方法
def insert_data_to_database(self, ticker_name, api_data_dict):
self.connect_to_database()
sqlite_insert_data_query = '''INSERT INTO {}(open_price, high_price, low_price, previous_close_price, date)\
VALUES ({}, {}, {}, {}, 'data');'''.format(ticker_name,\
api_data_dict['o'],\
api_data_dict['h'],\
api_data_dict['l'],\
api_data_dict['pc'])
cursor = self.sqliteConnection.cursor()
cursor.execute(sqlite_insert_data_query)
cursor.close()
self.close_connection()
这是我的示例测试。
name = 'NIO'
data = {'o': 24.123, 'h': 30.02, 'l': 22.03, 'pc': 23}
test = SQLDatabaseOperator()
test.insert_data_to_database(name, data)
数据库中没有任何内容。我不知道该怎么办。我正在使用 SQLite。这是我的数据库。
【问题讨论】:
-
确保在 INSERT 查询之后调用
self.sqliteConnection.commit()。 -
@mechanical_meat 在 cursor.execute() 之前还是之后?
-
在
cursor.execute()之后,但在您关闭连接之前。 -
@mechanical_meat 非常感谢,它解决了我的问题!
-
干杯,伙计。祝您编码愉快!