在python中创建一个数据库,用户在其中输入数据?



我希望程序向用户询问信息(即年龄和姓名(,并将此信息放入数据库。

我尝试了以下方法:

import sqlite3
connection = sqlite3.connect("Students.db")
cursor = connection.cursor()
sql_command = """
CREATE TABLE age_name ( 
age INTEGER PRIMARY KEY,   
name VARCHAR(50));"""
cursor.execute(sql_command)
for s in range(0,20):
student_name=input('Students Name: ')
student_age=input(' Students Age: ')
new_data = ("""INSERT INTO age_name (student_age, student_name)
VALUES ({},{});""".format(age,name))
cursor.execute(new_data)

不断出现的错误是:

cursor.execute(new_data)
OperationalError: no such column: 'James'

我有Python 3.7,我在spyder工作。

试试这个,

import sqlite3
connection = sqlite3.connect("Students.db")
cursor = connection.cursor()
sql_command = """
CREATE TABLE age_name ( 
age INTEGER PRIMARY KEY,   
name VARCHAR(50));"""
cursor.execute(sql_command)
for s in range(0, 20):
student_name = input('Students Name: ')
student_age = input(' Students Age: ')
new_data = ("""INSERT INTO age_name (age, name)
VALUES ({},'{}');""".format(student_age, student_name))
cursor.execute(new_data)

student_name是一个字符串,应括在单引号中。

正如@Sushanth正确指出的那样,您应该将代码中的".format(age,name(("更改为".format(student_age,student_name(("。 此外(虽然不是你的问题(,你不应该把年龄作为主键。

相关内容

最新更新