Skip to content
Advertisement

Create a database in python where user inputs the data?

I would like the program to ask the user for information (i.e. age and name) and for this information to be put into the database.

I have tried the following:

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)

The error that keeps appearing is:

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

I have Python 3.7 and I work in spyder.

Advertisement

Answer

Try this,

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 is a string and should be enclosed in single quotes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement