I have made a database using python. I have made a class to manipulate the database to insert a record 'Charlie' into the database however an error occurs. The error seems a bit vague and I can't figure out what is causing it.
import sqlite3
class create_db: # class to create database
def __init__(self):
self.conn = sqlite3.connect("EXAMPLE.db") # connects to database
self.c = self.conn.cursor()
def create_tables(self, Tables): # for each table in Tables, create table with field and table names
for table_name, field in Tables.items():
self.c.execute('CREATE TABLE IF NOT EXISTS ' + table_name + '(' + field + ')') # creates table
self.conn.commit()
class customer_table(create_db):
def __init__(self):
super().__init__()
def data_entry(self, Customer_Name): # adds a record to database
self.data_tuple = (Customer_Name,)
self.sql = 'INSERT INTO CUSTOMERS(CustomerID, Customer_Name), values(?,?)' # sql to inset into customers
self.c.execute(self.sql, self.data_tuple)
self.conn.commit()
def main():
db = create_db()
tables = {"CUSTOMERS": '''CustomerID integer,
Customer_Name text,
primary key (CustomerID)'''} # Dictionary of tables and fields
db.create_tables(tables)
customer = customer_table()
customer.data_entry("Charlie")
main()
Error: self.c.execute(self.sql, self.data_tuple) sqlite3.OperationalError: near ",": syntax error
-
You need to figure out a way to see the SQL statement that is causing the error. If you put a try/except block around your SQL executions, then when you catch an error you could print the SQL that generated the error. Is that the whole error message that you show? Make sure you are putting the entire error message into your question, including any stack trace that you are getting with th error.CryptoFool– CryptoFool2023年01月24日 07:03:24 +00:00Commented Jan 24, 2023 at 7:03
1 Answer 1
Your sqlite insert isnt valid. An insert shouldnt have a comma before the values. you also need to pass 2 items in your data tuple as you have 2 bindings
class customer_table(create_db):
def __init__(self):
super().__init__()
def data_entry(self, Customer_Name): # adds a record to database
self.data_tuple = (123, Customer_Name)
self.sql = 'INSERT INTO CUSTOMERS(CustomerID, Customer_Name) values(?,?)' # sql to inset into customers
self.c.execute(self.sql, self.data_tuple)
self.conn.commit()
answered Jan 24, 2023 at 7:08
Chris Doyle
12.4k2 gold badges30 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default