Python sqlite3 and string formatting - Error - python-3.x

This is my code:
title = "Importunate Widow"
conn = sqlite3.connect('parable.sqlite')
c = conn.cursor()
sqlite3.enable_callback_tracebacks(True)
c.executescript("""
CREATE TABLE IF NOT EXISTS _index(
title text NOT NULL,
context text NOT NULL
);
CREATE TABLE IF NOT EXISTS {}(
value int NOT NULL,
number int NOT NULL,
question text NOT NULL,
choice1 text,
choice2 text,
choice3 text,
choice4 text,
answer text NOT NULL,
explanation text,
see text
)""".format(title))
c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)
c.executemany('INSERT INTO {}(value,number,question,choice1,choice2,choice3,choice4,answer,explanation,see) VALUES(?,?,?,?,?,?,?,?,?,?)'.format(title), quiz)
conn.commit()
conn.close()
This gives me:
OperationalError Traceback (most recent call last)
/home/user/Hobby/Quiz/quiz_sqlite.py in <module>()
sqlite3.enable_callback_tracebacks(True)
87
---> 88 c.executescript("""CREATE TABLE IF NOT EXISTS _index(title text NOT NULL,context text NOT NULL);CREATE TABLE IF NOT EXISTS {}(value int NOT NULL,number int NOT NULL,question text NOT NULL,choice1 text,choice2 text,choice3 text,choice4 text,answer text NOT NULL,explanation text,check text )""".format(title))
89
90 c.executemany('INSERT INTO _index(title,context) VALUES(?,?)', index)
OperationalError: near "Widow": syntax error
I am basically iterating over multiple files and inserting data into tables named after the files. I have searched the internet and have turned up with nothing.
What I tried:
Tried adding ; after the ) before """
Tried adding , after see text
Tried changing the name of the column see to refer
None of this helped!
What is the syntax error in the code?

You're trying to use Importunate Widow as a table name. You're not allowed to use spaces in a table or field name.

Related

Incorrect number of bindings supplied. The current statement uses 11, and there are 10 supplied

I´m Learning Coding and the Error Message from the Debugging confuse me a bit,
when i try to create a SQLlite Database with 11 statements, i have two different Errors.
here my Code:
import sqlite3
connection = sqlite3.connect("wtime1.db")
cursor = connection.cursor()
date = ("31.10.2022")
p_unit = ("MMO")
equip = ("D014-K-00001")
report_prio = ("1")
order_prio = ("2")
job = ("Oel wechsel")
w_time = ("120")
fte = ("2")
reason = ("Kein Oel vorhanden")
cause = ("MAR 2")
solved = ("Erledigt")
mar2_list = ([date, p_unit, equip, report_prio, order_prio, job, w_time, fte, reason, cause, solved])
cursor.execute("create table if not exists mar21 (DATE integer, P_UNIT text, EQUIP text, REPORT_PRIO text, ORDER_PRIO text, JOB text, W_TIME integer, FTE integer, REASON text, CAUSE text, SOLVED text)")
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
the first Error:
Incorrect number of bindings supplied. The current statement uses 11, and there are 10 supplied.
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
Okay i found in my search i need one more comma at the end of the Values
when i set the comma like this
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i have a syntax error
near ")": syntax error
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i think i´m running a wrong way with the "insert values" line!
since you have one record use execute instead of executemany
cursor.execute("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)

Python3 Sqllite Normal query works but not while passing it a tuple

I have a Db from where I have to display all the columns which match the substring of the column given by user.
The following code works:
c.execute("select *from Transactions where Description like '%sh%' ")
conn.commit()
print(c.fetchall())
conn.close()
But when I try to run this code it returns me an empty list:
def search(col,val):
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("Select *from Transactions where ? Like ? ",(col,'%'+val+'%'))
print(c.fetchall())
search('description',"sh")
Also the result will always be a blank list even if the col name is wrong. as opposed the usual error which says column not found.
Please Help

Deleting a sqlite3 database Row in python

I have been reading a number of threads on how to accomplish this but for some reason it is not working.
I need to delete a Row from a database using a string variable from an entry widget as the "WHERE (variable name)=" is used in the DB query.
The entry widget data is stored as Snippet_Name and the same name is being used as a column name in the DB.
The database has 7 columns but I am only using the 1 column for the query and I want to delete the complete row which contains the entry variable. I have tried variations of DELETE with no success.
The code being used is:
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = "?"', (snippetname))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')
A little help and hint would be appreciated.
I went over the query and found 2 errors that needed to be address to correct the problem. The first problem was I had the ? enclosed in quotations which should not be there. Second problem was forgetting to a comma to the variable.
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = ?' (snippetname,))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')

How to fix " sqlite3.OperationalError: incomplete input " when the error is regarding ''')

This is the error I am getting:
Traceback (most recent call last): File "/Users/My
Documents/Independent Learning/BBA Coding Related Work/Creating a
Database with SQLite3 for Python/MarketCo1.py", line 89, in
'''); sqlite3.OperationalError: incomplete input
Below is the code I used:
cursor.execute('''CREATE TABLE ContactEmployee(
ContactEmployeeID INTEGER PRIMARY KEY,
ContactID INTEGER, EmployeeID INTEGER,
ContactDate NUMERIC,
Description TEXT,
FOREIGN KEY(ContactID) REFERENCES Contact(ContactID),
FOREIGN KEY(EmployeeID) REFERENCES Employee(EmployeeID)
''')
db.commit()
You are missing a closing brace, as mentioned by glibdud in the comments:
cursor.execute('''CREATE TABLE ContactEmployee(
ContactEmployeeID INTEGER PRIMARY KEY,
ContactID INTEGER, EmployeeID INTEGER,
ContactDate NUMERIC,
Description TEXT,
FOREIGN KEY(ContactID) REFERENCES Contact(ContactID),
FOREIGN KEY(EmployeeID) REFERENCES Employee(EmployeeID))
''')
db.commit()

psycopg2 programming error while creating table

In a Python2.7 script, the following gave me an error, I can't figure out why:
import psycopg2
conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()
curs.execute("CREATE TABLE newtable;")
The error looks like:
Traceback (most recent call last):
File "<ipython-input-17-f4ba0186c40c>", line 1, in <module>
curs.execute("CREATE TABLE newtable;")
ProgrammingError: syntax error at or near ";"
LINE 1: CREATE TABLE newtable;
Any SELECT statement works perfectly well on the other hand. For example:
curs.execute("SELECT * FROM table1 LIMIT 0;")
works like a charm.
CREATE TABLE newtable; is not the correct syntax to create a new table. You need to define some columns.
CREATE TABLE newtable (
foo INTEGER,
bar TEXT
);
See the CREATE TABLE docs for more info.

Resources