简体   繁体   中英

can i escape this error Traceback (most recent call last): File “<stdin>”, line 1, in <module> File “<stdin>”, line 2, in data_entry

I'm trying to put some info into the database

import sqlite3
conn = sqlite3.connect("tutorial.db")
c=conn.cursor()
def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS stuffPlot(unix REAL,datestamp Text,keyword TEXT,value REAL)")
def data_entry(x,y,z,w):
    c.execute("INSERT INTO stuffPlot VALUES({},{},{},{})".format(x,y,z,w))
    conn.commit()
    c.close()
    conn.close()
x=int(input("enter a number"))
y=str(input("enter a str"))
z=int(input("enter a number"))
w=str(input("enter a str"))
create_table()
data_entry(x,y,w,z)

I want to write to the database, but it creates the following database error:

data_entry(x,y,w,z) Traceback (most recent call last): File "", line 1, in File "", line 2, in data_entry sqlite3.OperationalError: no such column: name

Your strings are missing quotes so they're treated as column names, try this:

c.execute("INSERT INTO stuffPlot VALUES({},'{}','{}',{})".format(x,y,z,w))

Edit

Instead of the line above (which is vulnerable to SQL Injection) you should do it like this:

c.execute("INSERT INTO stuffPlot VALUES(?,?,?,?)", (x,y,z,w))

Hey your last line is calling this:

data_entry(x,y,w,z)

Its x,y,w,z, but in your function definition you are receiving this:

def data_entry(x,y,z,w): #sequence is x,y,z,w

So that created a bit confusion on what variable is what. And also your strings will need to be enclosed inside single quotes as @scope mentioned.

So here's a working code

import sqlite3
conn = sqlite3.connect("tutorial.db")
c=conn.cursor()
def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS stuffPlot(unix REAL,datestamp Text,keyword TEXT,value REAL)")
def data_entry(x,y,z,w):
    c.execute("INSERT INTO stuffPlot VALUES({},'{}',{},'{}');".format(x,y,z,w)) 
    #fixed the quotes above
    conn.commit()
    c.close()
    conn.close()
x=int(input("enter a number"))
y=str(input("enter a str"))
z=int(input("enter a number"))
w=str(input("enter a str"))
create_table()
data_entry(x,y,z,w) #fixed x,y,w,z to x,y,z,w

If you have any doubt please comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM