sqlite3.OperationalError: near "X": syntax error in CREATE TABLE statement

Question:

This code:

conn = connect('emails.db')
curs = conn.cursor()

curs.execute('''create table items
  (integer primary key, X, Y)''')

curs.execute("INSERT INTO items (integer primary key, X, Y) VALUES ('today', 'X', 'Y')")

connection.commit()

returns:

sqlite3.OperationalError: near
“primary”: syntax error

How come? I don’t see what I’m doing wrong. The values I’m putting in there are all variables btw.

Asked By: HankSmackHood

||

Answers:

Your CREATE TABLE is incorrect: it doesn’t specify a name for the first (‘integer primary key’) column. SQLite now thinks that the field is named integer, and has no data type defined. You probably wanted to have an INTEGER PRIMARY KEY field, because that is very efficient. To do so, respect the CREATE TABLE syntax, and give it a name:

CREATE TABLE items
( id INTEGER PRIMARY KEY
, x  DOUBLE
, y  DOUBLE
);

As a side note: I’ve defined X and Y as doubles, since specifying the type is just good practice, and is also slightly more efficient. Of course, if you want to put text in them, define them as TEXT. Or if you want them to contain primarily integers, define them as INTEGER. Only ever leave out the data type if you really don’t know what kind of data you’ll be putting in there.

Next, since the INSERT statement only expects field names (and not their full definition), SQLite throws a Syntax Error — rightly so.

And finally, don’t you think it a bit silly to put ‘today’ (a text value) into an integer column?!?


Edit: since you say X and Y are variables, might as well put you on the right track at to binding those variables to the SQL statement:

curs.execute("INSERT INTO items (X, Y) VALUES (:X, :Y)", {X: X, Y: Y})

I’ve left out the id primary key field, since SQLite will automatically generate that if it’s not present. If you want to pass an explicit value, you can. But take care that it is an integer, and that it is unique!

The :X and :Y parameters in the SQL statement refer to the X and Y members of the dictionary that is passed as second parameter to the execute statement.

Binding parameters is both safer and faster than including the parameters into the SQL string itself.

Answered By: Martijn
import sqlite3
conn=sqlite3.connect('sqlite.db')
conn.execute('''
        Creat: table student (
           st_id INT AUTO INCREMENT PRIMARY KEY,
           st_name VARCHAR(50),
           st_class VARCHAR(10),
           st_class VARCHAR(30)
        )
        ''')
conn.close()
Answered By: SUSHIL SHIRSATH
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.