与python一起使用sqlite3时出错

时间:2015-02-20 23:02:09

标签: python-2.7 sqlite

import sqlite3


conn = sqlite3.connect('test.db')
cur=conn.cursor()

cur.execute("DROP TABLE IF EXISTS students")
cur.execute('''CREATE TABLE students(name text, age text)''')
cur.execute("INSERT INTO students VALUES ('john','22')")
cur.execute("INSERT INTO students VALUES ('kris','33')")
cur.execute("INSERT INTO students VALUES ('mathew','25')")
cur.execute("INSERT INTO students VALUES ('sarah','40')")

conn.commit()

ageofstudent = '25'

cur.execute("SELECT name FROM students WHERE age =?",ageofstudent)

print [str(record[0]) for record in cur.fetchall()]

conn.close()

你好朋友..我正在用这个简单的例子来帮助你。我不明白为什么我在执行这个简单的代码时遇到错误。我是sqlite3数据库的新手。错误如下所示

> >>> 
> 
> Traceback (most recent call last):   File "C:/Users/labuser/Google
> Drive/Smart Lab Projects/wireshark lte signalling
> parser/foroverstock.py", line 18, in <module>
>     cur.execute("SELECT name FROM students WHERE age =?",ageofstudent) ProgrammingError: Incorrect number of bindings supplied. The current
> statement uses 1, and there are 2 supplied.
> >>>

1 个答案:

答案 0 :(得分:0)

看起来sqlite3cursor.execute的参数需要iterable。您需要将其称为:

cur.execute("SELECT name FROM students WHERE age =?", (ageofstudent,))

因为它期望迭代,所以它将'25'的'2'和'5'视为单独的参数。