sqlite3.OperationalError: unrecognized token: "\" - python

import sqlite3
con=sqlite3.connect("mydbmb")
con.execute('''CREATE TABLE IF NOT EXISTS LOGIN
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
ROLL INT NOT NULL,
photo BLOB NOT NULL,
phone INTEGER NOT NULL,
father TEXT NOT NULL,
PASS TEXT NOT NULL);''')
with open("7.jpg", 'rb') as file:
blobdata = file.read()
quer=f'''INSERT INTO LOGIN(NAME,ROLL,photo,phone,father,PASS) VALUES('ADMIN','000','{blobdata}','678642873','GHHGJH','ADMIN123')'''
con.execute(quer)
print("query executed succsessfully")
user_list()
con.close()

Using literal parameters values (i.e. putting the values in the query) is error prone and insecure (unless they are constant)
It is much better to use bound parameters :
quer = '''INSERT INTO LOGIN(NAME,ROLL,photo,phone,father,PASS) VALUES(?, ?, ?, ?, ?, ?)'''
con.execute(quer, ('ADMIN','000', blobdata,'678642873','GHHGJH','ADMIN123'))
print("query executed successfully")

Related

SQLITE3.OperationalError: near ")": syntax error when creating database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I can't seem to be able to see for myself, what when wrong in this line of codes, have been staring at it for the last 20 min but I can't seem to figure anything out.
here is the error:
Traceback (most recent call last):
File "C:\Users\usera\PycharmProjects\itptesting_2\itptesting\init_db.py", line 7, in <module>
connection.executescript(f.read()),
sqlite3.OperationalError: near ")": syntax error
and the fullcode:
import sqlite3
connection = sqlite3.connect('database.db')
with open('schema.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('First Post', 'Content for the first post')
)
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('Second Post', 'Content for the second post')
)
cur.execute("INSERT INTO users (fullname, email, password) VALUES (?, ?, ?)",
('UserA', 'user#demo.com', 'asdfghjkl')
)
cur.execute("INSERT INTO entries (stockname, partnum, company, quantity, uom, remarks) VALUES (?, ?, ?, ?, ?, ?)",
('Beer','Albee0001','RES','24','BTL','new stock for promotions ')
)
connection.commit()
connection.close()
and schema.sql
DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
content TEXT NOT NULL
);
DROP TABLE IF EXISTS signup;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fullname TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
);
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded NOT NULL DEFAULT CURRENT_TIMESTAMP,
remarks TEXT NULL,
FOREIGN KEY(id) REFERENCES users(id),
);
I had tried deleting the database.db file and regenerating it by run init_db.py but it still gave me the same error. What should I do?
You have a couple of problems, this is the correct syntax:
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stockname TEXT NOT NULL,
partnum TEXT NOT NULL,
company TEXT NOT NULL,
quantity INTEGER NOT NULL,
uom TEXT NOT NULL,
date_recorded DATE NOT NULL DEFAULT (CURRENT_TIMESTAMP),
remarks TEXT,
FOREIGN KEY(id) REFERENCES users(id)
);

python sqlite foreing keys not deleting on cascade

So I have 2 files, a client and a db class:
import sqlite3
from os.path import isfile
class Database:
def __init__(self, db_name):
self.db_name = db_name
self.check = self.__check_db()
self.conn = sqlite3.connect(self.db_name, check_same_thread=False)
self.cursor = self.conn.cursor()
if not self.check:
self.__create_db()
def query(self, query, args=()):
self.cursor.execute(query, args)
result = self.cursor.fetchall()
self.conn.commit()
return result
def __check_db(self):
return isfile(self.db_name)
def __create_db(self):
self.cursor.executescript("""
PRAGMA FOREIGN_KEYS = ON;
CREATE TABLE utilizadores (id INTEGER PRIMARY KEY, nome TEXT, senha TEXT);
CREATE TABLE artistas (id INTEGER PRIMARY KEY, id_spotify TEXT, nome TEXT);
CREATE TABLE musicas (id INTEGER PRIMARY KEY, id_spotify TEXT, nome TEXT, id_artista INTEGER, FOREIGN KEY(id_artista) REFERENCES artistas(id) ON DELETE CASCADE);
CREATE TABLE avaliacoes (id INTEGER PRIMARY KEY, sigla TEXT, designacao TEXT);
CREATE TABLE playlists (id_user INTEGER, id_musica INTEGER, id_avaliacao INTEGER, PRIMARY KEY (id_user, id_musica), FOREIGN KEY(id_user) REFERENCES utilizadores(id) ON DELETE CASCADE, FOREIGN KEY(id_musica) REFERENCES musicas(id) ON DELETE CASCADE, FOREIGN KEY(id_avaliacao) REFERENCES avaliacoes(id) ON DELETE CASCADE);
INSERT INTO avaliacoes (id, sigla, designacao) VALUES (1, "M", "Medíocre"), (2, "m", "Mau"), (3, "S", "Suficiente"), (4, "B", "Boa"), (5, "MB", "Muito Boa");
""")
and the client;
from database import Database
db = Database("spotify.db")
db.query("insert into artistas (id_spotify, nome) values (?, ?)", ("1", "The Beatles"))
db.query("insert into musicas (id_spotify, nome, id_artista) values (?, ?, ?)", ("m1", "Hey Jude", 1))
db.query("delete from artistas where id = ?", (1,))
If I do the last query because of the foreign key it should delete the music as well but for some reason it doesn't. I don't know the reason for why it's doing it since I have PRAGMA fk = on and I'm on the same connection
artistas --> artists
musicas --> musics
PRAGMA FOREIGN_KEYS = ON operates on a per connection basis and this means that you must set it for every connection object that you obtain (if you want the behavior that it provides, otherwise don't set it because it may decrease performance).
Inside the Database class define:
def set_foreign_keys(self)
self.conn.execute("PRAGMA FOREIGN_KEYS = ON")
and use it in the client:
from database import Database
db = Database("spotify.db")
db.set_foreign_keys()
db.query("insert into artistas (id_spotify, nome) values (?, ?)", ("1", "The Beatles"))
db.query("insert into musicas (id_spotify, nome, id_artista) values (?, ?, ?)", ("m1", "Hey Jude", 1))
db.query("delete from artistas where id = ?", (1,))

How to take table name from user input in flask?

#app.route("/CreateAScheme",methods=['GET','POST'])
def CreateAScheme():
if request.method == 'POST':
userDetails = request.form
Scheme = userDetails['Scheme']
con = MySQL.connection.cursor()
con.execute("CREATE TABLE %s (id int NOT NULL AUTO_INCREMENT, Course varchar(255) NOT NULL, Year varchar(255), PRIMARY KEY(id));",(Scheme))
MySQL.connection.commit()
con.close()
flash("Succesfully Created")
return "Succesfully"
return render_template('index.html')
I am Getting an Error "not all arguments converted during string formatting"
Simply wrapping a variable in parentheses, like you're doing in (Scheme) does nothing.
.execute() expects a parameter tuple, no matter if it's just an 1-tuple, i.e. (Scheme,):
con.execute(
"CREATE TABLE %s (id int NOT NULL AUTO_INCREMENT, Course varchar(255) NOT NULL, Year varchar(255), PRIMARY KEY(id));",
(Scheme,)
)
con.execute("CREATE TABLE %s (id int NOT NULL AUTO_INCREMENT, Course varchar(255) NOT NULL, Year varchar(255), PRIMARY KEY(id));" %(Scheme))
"Just Use regular % interpolation"
Thank You #AKX

AUTOINCREMENT column field asks for an input value

I've created a database with an autoincremented field:
filecur.execute("CREATE TABLE IF NOT EXISTS File_Data (_FID INTEGER PRIMARY KEY AUTOINCREMENT, UID INTEGER(1000000), FileName varchar2 (15), Date_ varchar2 (15))")
filecur.execute("insert into File_Data values (?, ?, ?)", (uid, filename, today))
However, when I try to insert values in this table, I get an error that says that I've supplied only 3 values in a table with 4 fields. Isn't autoincrement supposed to work on its own, or am I missing something? Any help would be appreciated, thanks!
You have to specify which columns you're inserting, e.g.:
filecur.execute("insert into File_Data(UID, FileName, Date_) values(?, ?, ?)",
(uid, filename, today))
Note that you could insert the autoincrement field explicitly, e.g.:
filecur.execute("insert into File_Data(FID_, UID, FileName, Date_) values (?, ?, ?, ?)",
(fid, uid, filename, today))
But normally you wouldn't be doing that.

Mysql Python: Not all parameters were used in MySQL statement

So I am trying to input data into my table as variables but I seem to keep on getting the error mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement, I have used the %s instead of the row names but I seem to keep on getting the same error. I suspect it is my syntax but I cannot seem to figure it out btw this is my first time using python and MySQL together
import mysql.connector
Sensor_ID = "test"
Location = "room"
Sensor_IP = "192.168.1.1"
Sensor_1 = "10"
Sensor_1_Unit = "*C"
Sensor_2 =""
Sensor_2_Unit = ""
Sensor_3 = ""
Sensor_3_Unit = ""
conn = mysql.connector.connect(user='******', password='********', host='******', database='*****') #blanked my user n pass
mycursor = conn.cursor()
mycursor.execute('SHOW TABLES')
print(mycursor.fetchall())
print ""
mycursor.execute("SHOW VARIABLES LIKE '%version%'")
print "Version:",(mycursor.fetchall())
#works up to here
mycursor.execute("INSERT INTO iot_sensors VALUES (ID, Sensor_ID, Location, Sensor_IP, Sensor_1, Sensor_1_Unit, Sensor_2,Sensor_2_Unit, Sensor_3, Sensor_3_Unit)",(Sensor_ID,Location,Sensor_IP,Sensor_1,Sensor_1_Unit,Sensor_2,Sensor_2_Unit,Sens or_3,Sensor_3_Unit))
conn.commit()
# Sensor_ID,Location,Sensor_IP,Sensor_1,Sensor_1_Unit,Sensor_2,Sensor_2_Unit,Sensor_3,Sensor_3_Unit
CREATE TABLE IoT_Sensors(
ID INT NOT NULL AUTO_INCREMENT,
Sensor_ID VARCHAR (15) NOT NULL,
Location VARCHAR (20) NOT NULL,
Sensor_IP VARCHAR (15) NOT NULL,
Sensor_1 VARCHAR (15) NOT NULL,
Sensor_1_Unit VARCHAR (15) NOT NULL,
Sensor_2 VARCHAR (15),
Sensor_2_Unit VARCHAR (15),
Sensor_3 VARCHAR (15),
Sensor_3_Unit VARCHAR (15),
Time_Stamp TIMESTAMP NOT NULL,
PRIMARY KEY (ID));
You need to put %s into your SQL statement.
mycursor.execute("INSERT INTO iot_sensors VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",(Sensor_ID,Location,Sensor_IP,Sensor_1,Sensor_1_Unit,Sensor_2,Sensor_2_Unit,Sens or_3,Sensor_3_Unit))
See the example in the docs.
Looks like you are missing formatting your actual variables from the insert statement. Try formatting them using one of the known methods, %s or .format method. You are also not using the timestamp, last column, value in your table when inserting. If you just reference the table you will have a column mismatch. You will have to be explicit about what columns you are populating. You could use CURRENT_TIMESTAMP for that since it says NOT NULL for column description.
query = ("""Insert into iot_sensors (Sensor_ID, Location, Sensor_IP, Sensor_1, Sensor_1_Unit, Sensor_2, Sensor_2_Unit, Sensor_3, Sensor_3_Unit) values
('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');""".format(Sensor_ID,Location,Sensor_IP,Sensor_1,Sensor_1_Unit,Sensor_2,Sensor_2_Unit,Sensor_3,Sensor_3_Unit))
mycursor.execute(query)
or
query = ("""Insert into iot_sensors (Sensor_ID, Location, Sensor_IP, Sensor_1, Sensor_1_Unit, Sensor_2, Sensor_2_Unit, Sensor_3, Sensor_3_Unit) values
(%s,%s,%s,%s,%s,%s,%s,%s,%s);""" % (Sensor_ID,Location,Sensor_IP,Sensor_1,Sensor_1_Unit,Sensor_2,Sensor_2_Unit,Sensor_3,Sensor_3_Unit))
mycursor.execute(query)

Categories

Resources