简体   繁体   中英

Syntax Error- in Sqlite3 code when inserting data in table

I am writing a code to make a basic table and insert data into it using Sqlite3 in Python 3. The CMD is showing syntax error by putting a pointer at a data set.

import sqlite3
conn=squlite3.connect('name.sqlite')
cur=conn.cursor()
cur.execute('CREATE TABLE Ages (name TEXT, age INTEGER)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Abiha', 33)')
cur.execute('INSERT INTO Ages (name, age) VALUES ('Catrin', 29)')
conn.commit()
cur.execute('SELECT name,age FROM Ages')
for row in cur:
    print(row)
conn.close()

This is what the CMD shows:

cur.execute('INSERT INTO Ages (name, age) VALUES ('Cael', 16)')
                                                   ^
SyntaxError: invalid syntax

If you know what is wrong with it please let me know!

You are using single quotes for your execute statements, this is causing Python to see Cael , Abiha and Catrin as an expected variable or keyword.

Change your execute statements to use double quotes like so:

cur.execute("CREATE TABLE Ages (name TEXT, age INTEGER)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Cael', 16)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Abiha', 33)")
cur.execute("INSERT INTO Ages (name, age) VALUES ('Catrin', 29)")

You could also escape them like so \' but the above is better.

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