python + sqlite, insert data from variables into table

Posted on

python + sqlite, insert data from variables into table – This article will take you through the common SQL errors that you might encounter while working with python, sql,  sqlite. The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue. SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem.

SQL Problem :

I can insert hardcoded values into an SQLite table with no problem, but I’m trying to do something like this:

name = input("Name: ")
phone = input("Phone number: ")
email = input("Email: ")

cur.execute("create table contacts (name, phone, email)")
cur.execute("insert into contacts (name, phone, email) values"), (name, phone, email)

I know this is wrong, and I can’t find how to make it work. Maybe someone could point me in the right direction.

Solution :

You can use ? to represent a parameter in an SQL query:

cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
            (name, phone, email))

cur.executemany(“insert into contacts (name, phone, email) values (?, ?, ?)”,
(name, phone, email))

cur.execute("create table contacts (name, phone, email)")

cur.execute("insert into contacts (name, phone, email) values(?,?,?)",(name, phone, email)) 

OR

cur.execute("insert into contacts values(?,?,?)",(name, phone, email))

As you are inserting values to all available fields, its okay not to mention columns name in insert query

Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code.

Leave a Reply

Your email address will not be published. Required fields are marked *