【问题标题】:Extracting values from SQLite database in Python在 Python 中从 SQLite 数据库中提取值
【发布时间】:2012-02-06 15:42:00
【问题描述】:

我试图弄清楚如何使用 python 使用 SQLite 数据库,但似乎被卡住了。我想我缺少一些基本的东西。我正在关注本教程:http://docs.python.org/library/sqlite3.html

我建立了一个数据库,使其包含以下信息:

import sqlite3
conn = sqlite3.connect('SQL_test_3') #this creates a seperate file
c = conn.cursor()
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)''')
data = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]

for t in data:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

conn.commit()

c.close()

当我尝试提取数据时,我的问题出现了;本教程解释了如果满足其中一个特征,如何提取数据,例如:

(当我在另一个文件中打开数据库时)

import sqlite3

conn = sqlite3.connect('SQL_test_3')

c = conn.cursor()

price = 53
t = (price,)
c.execute('select * from stocks where price=?', t)
print c.fetchall()

上面的方法很完美,但是如果我想提取价格大于 50 的所有资产的信息怎么办,我做不到。做价格> 50和价格>?没用……

所以我的问题是:

1) 当关键标准符合给定范围时,我如何提取资产的信息,例如价格 > 50 或 40

2)如果我想要两个标准,例如 IBM 股票的信息,以及 如果股票的交易价格高于 50。

我觉得我的问题非常初级/基本,但在教程中找不到答案。

感谢任何帮助。

提前致谢。

【问题讨论】:

  • 我尝试运行您的代码,它对我来说很好。请发布您尝试使用 > 的确切代码以及运行它时得到的输出。
  • 这肯定是 SQL 问题,而不是 Python 问题?
  • 邓肯,我得到了这条线:price = 50 t = (price,) c.execute('select * from stock where price>?', t) z4 = c.fetchall( ) 打印 z4 谢谢

标签: python sqlite


【解决方案1】:
c.execute('select * from stocks where price > ?', (50,))

c.execute('select * from stocks where price between ? and ?', (40, 70))

c.execute('select * from stocks where price > ? and symbol = ?', (50, 'IBM'))

这样可以吗?还是需要通用解决方案?

【讨论】:

  • 第一个行不通:你需要一个元组而不是单个值。
  • 你的第一行和第二行仍然不适合我。你的第 3 行工作正常。谢谢。
  • 好的。问题出在我头上。我知道了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多