如何使用sqlite从数据库中的同一行读取单个值?

时间:2016-03-29 16:01:02

标签: python sqlite

我试图从数据库中的同一行读取2个值,但我只能一次读取整行。我添加了我认为相关的所有代码:

    def find(search, term):
        # Helper function for the find function.
        with connect("GTINb.db") as db:
            cursor = db.cursor()
            sql = "select * from GTINb where {} = ?".format(search)
            cursor.execute(sql,(term,))
            db.commit()
            results = cursor.fetchall()
            new = str(term)
            if results:
                results = str(results)
                temp = open('temp.txt', 'a')
                temp.write(results)
                temp.write('\n')
                temp.close()
                with connect("GTINb.db") as db:
                    cursor.execute("UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)",(new,))
                    cur = cursor.execute("SELECT stockcur from GTINb by (?)",(new,))
                    re = cursor.execute("SELECT restock from GTINb by (?)",(new,))
                    if cur < re:
                        cursor.execute("UPDATE GTINb SET stockcur=stockcur+10 WHERE GTIN8=(?)",(new,))
                        return print('More stock has been ordered in as stocks were low')
                    else:
                        return
            else:
                temp = open('temp.txt', 'a')
                temp.write('Product not found')
                temp.write('\n')
                temp.close()
                return 

我目前收到错误sqlite3.OperationalError: near "(": syntax error,并尝试用%s代替'(?)',(%s)和?没有成功,提出以下错误消息:

sqlite3.OperationalError: near "12345670": syntax error // where 12345670 was the input represented by new
sqlite3.OperationalError: near "(": syntax error 
sqlite3.OperationalError: near "?": syntax error 

还有其他方法可以做到这一点,还是我犯了一个简单的错误?

1 个答案:

答案 0 :(得分:1)

您编写的所有SQL语句都不是有效的SQL。有关有效的语法,请参阅SQLite documentation

简言之:

 UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)
 SELECT stockcur from GTINb by (?)
 SELECT restock from GTINb by (?)

应该是

 UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8 = ?
 SELECT stockcur FROM GTINb WHERE GTIN8 = ?
 SELECT restock FROM GTINb WHERE GTIN8 = ?

虽然第一个可能会用不需要的括号执行。

一旦你的SQL工作,你会发现后两个语句可以组合成

 SELECT stockcur, restock  FROM GTINb WHERE GTIN8 = ?

我认为这就是你所要求的。