gpt4 book ai didi

python - 如何在sqlite 3中将数据添加到表中而不换行

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:00 25 4
gpt4 key购买 nike

我使用sqlite来保存一系列有关股票的数据,例如买入价、卖出价、趋势买入价等。我添加了价格,这很好,但是当我添加趋势时,它会显示到新的一行中,如何将其添加到与其他数据一致的位置?我尝试过使用替换和更新,但它仍然会导致我的其他列不返回任何内容,这会导致我的代码出现问题。

我的代码如下

def plot():
for a in stock:
count1 = 0
count2 = 1
index = 0
value = ["0"]
cursor.execute("""SELECT BuyPrice FROM """+a+"""""")
trend = []
rows = cursor.fetchall()
for row in rows:
print(row[0])
trend.append(float(row[0]))
index = index + 1
if index == len(web):
percentage = []
for i in range(len(web)-1):
change = trend[count2]-trend[count1]
print(trend[count2],trend[count1])
percent = (change/trend[count1])*100
print(percent)
percentage.append(percent)
count1 = count1 + 1
count2 = count2 + 1
for i in percentage:
print(i)
if i <= 0:
if i == 0:
value.append(0)
elif i <= -15:
value.append(-4)
elif i <= -10:
value.append(-3)
elif i <= -5:
value.append(-2)
elif i < 0:
value.append(-1)
else:
if i >= 15:
value.append(4)
elif i >= 10:
value.append(3)
elif i >= 5:
value.append(2)
elif i >= 0:
value.append(1)

for i in value:
t = str(i)
cursor.execute("""
REPLACE INTO """+ a +"""
(TrendBuy)
VALUES
("""+ t +""")
""")

this is what i mean if its a bit hard to understand

最佳答案

SQLite 的 REPLACE INTO需要一种“查找列”来查找值,然后替换下一个对应的值。如果不存在匹配项,它将插入一个新行。考虑将BuySell 合并到您的操作查询中。另外,下面还格式化 SQL 字符串并参数化查询:

cursor.execute("REPLACE INTO {} (BuySell, TrendBuy) VALUES (?, ?)".format(a), (row[0], t))

或者,您可以运行更新查询以避免无意插入,因为循环逻辑中不会生成新的 BuySell 值。

cursor.execute("UPDATE {} SET TrendBuy = ? WHERE BuySell = ?".format(a), (t, row[0]))

旁白 - 您似乎将每只股票存储在其自己的表中。为了提高效率、可扩展性和更轻松的查询,请考虑一个带有 StockName 或 Symbol 列的 Stock 表。

关于python - 如何在sqlite 3中将数据添加到表中而不换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com