sqlite3 database query in python - python

I tried performing a search query from the backend of an app I'm working and I got the response below:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
ValueError: parameters are of unsupported type
I have the code below:
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan Number TEXT, Tracing Number TEXT, Submitted By TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
rows = cur.fetchall()
conn.close()
return rows
self.NmRqst.text is the QLineEdit that accepts the user input for database query...
Feel free to correct the question as you deem fit!
I have edited the lines of code,
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan_Number TEXT, Tracing_Number TEXT, Submitted_by TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
rows = cur.fetchall()
conn.close()
return rows
...and I got the following error:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 64 supplied.

Related

Sqlite3 Change position column (reordering)

I have made this python method:
def move_player_list_item(start_position,end_position,player_list_item):
conn = create_connection()
query = "DELETE FROM `player_list` WHERE `position`=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),))
conn.commit()
if start_position<end_position:
query = "UPDATE `player_list` SET `position`=`position`-1 WHERE `position`>? AND `position`<=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),str(end_position)))
conn.commit()
elif end_position<start_position:
query = "UPDATE `player_list` SET `position`=`position`+1 WHERE `position`>=? AND `position`<?;"
cur = conn.cursor()
cur.execute(query,(str(end_position),str(start_position)))
conn.commit()
query = query = "INSERT INTO `player_list` (`play`, `relative_type`, `relative_number`, `repeats`, `duration_milliseconds`, `duration_human`,`position`) VALUES (?,?,?,?,?,?,?)"
cur = conn.cursor()
cur.execute(query,(str(player_list_item["play"]),str(player_list_item["relative_type"]),str(player_list_item["relative_number"]),str(int(player_list_item["repeats"])),str(int(player_list_item["duration_milliseconds"])),str(player_list_item["duration_human"]),str(end_position)))
conn.commit()
return 1
When start_position<end_position works with no error.
But when end_position<start_position there is an error:
Traceback (most recent call last):
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 977, in <module>
main()
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 925, in main
sqlite3_functions.move_player_list_item(30,20,player_list_items_db[29])
File "C:/Users/Χρήστος Παππάς/Έγγραφα/projects/Papinhio player/Αρχεία βάσης δεδομένων (Sqlite3)/../Αρχεία πηγαίου κώδικα εφαρμογής (Python)/Αρχεία κώδικα python (Python files)/Συναρτήσεις sqlite3 (Sqlite3 functions).py", line 1125, in move_player_list_item
cur.execute(query,(str(end_position),str(start_position)))
sqlite3.IntegrityError: UNIQUE constraint failed: player_list.position
The only solution i have thought about is to remove the unique constraint.
Is there any better solution?

SQLITE and PYQT5 stopping to respond on sql execution

I was building a todo app and used the sql-lite python database for it. I added the clear command and all was going well until I found out when I cleared the database and then tried to view it, my pyqt application just stopped responding.
The database code:
def db(self):
title = self.textEdit.toPlainText()
desc = self.textEdit_2.toPlainText()
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS task
(title text, desc text)
""")
cur.execute("INSERT INTO task VALUES(?,?)", (title, desc))
conn.commit()
cur.close()
conn.close()
the code to view the database [within qt application]
def showdb(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
str = ''
str2 = ''
self.tableWidget.setRowCount(50)
tableindex = 0
amount = len(cur.execute('SELECT * FROM task').fetchall())
if amount > 0:
for x in cur.execute('SELECT * FROM task'):
str = ''.join(x[0])
str2 = ''.join(x[1])
self.tableWidget.setItem(tableindex, 0, QtWidgets.QTableWidgetItem(str))
self.tableWidget.setItem(tableindex, 1, QtWidgets.QTableWidgetItem(str2))
tableindex += 1
else:
pass
the code to clear the database [it stops to respond after i click it]
def delete(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute('DROP TABLE task')
conn.commit()
The problem is in your delete function, after dropping the database you are not creating it again. This line of code should fix the error.
def delete(self):
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute('DROP TABLE task')
cur.execute("""CREATE TABLE IF NOT EXISTS task
(title text, desc text);
""")
conn.commit()

Inserting json data into a SQL Server table

import cursor as cursor
import requests
import pprint
import pyodbc
:
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MY-PC-PC;'
'Database=test;'
'Trusted_Connection=yes;')
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute('select * FROM test.dbo.books')
for row in cursor:
print(f'row = {row}')
print()
r = requests.get('https://5f97076911ab98001603b6d0.mockapi.io/api/v1/books')
# pprint.pprint(r.json()) #to print all the data
# pprint.pprint(r.json()[1]['author']) #to print user number 2 data
print(r.json()[1]['author'])
cursor = conn.cursor()
for i in range(50):
cursor.execute("INSERT INTO dbo.books (id, createdAt, title, author, imageUrl) "
"VALUES (r.json[i] ,r.json()[i]['createdAt'],r.json()[i]['title'], r.json()[i]['author'],r.json()[i]['imageUrl'] )")
conn.commit();
read(conn);
read(conn)
cursor.close()
I keep getting this error:
Traceback (most recent call last):
File "C:/Users/MY-PC/PycharmProjects/pythonProject2/py.py", line 40, in
cursor.execute("INSERT INTO dbo.books (id, createdAt, title, author, imageUrl) "
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'i'. (102) (SQLExecDirectW)")
Process finished with exit code 1
You are not using "i" or "r" as variables there, but as simple text. Try using a fstring, which would be putting an f before the "" and using {} to use your variables, as I do in this example:
name = "MyName"
print(f"Hello {name}")

sqlite3.OperationalError: no such table: store

I'm learning sqlite3 with python, but I've been facing this error: "sqlite3.OperationalError: no such table: store". How do I get around this?
import sqlite3
def create_table(): #function to create the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(item, quantity, price ): #function to insert into the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("INSERT INTO store VALUES(?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
insert("biscuits",500,20000)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
return rows
conn.close()
print(view())
You forgot to call the create_table method before calling insert. As you haven't called the the create_table method the insert method tries to insert a record to a non existing table.
The solution is simply to call the create_table method before insert as follows:
create_table() # Add this line before the insert
insert("biscuits", 500, 20000)

Python sqlite3 error about number of bindings supplied

I'm sure this has been asked, and answered before, but either I'm stupid or then none of the answers work for me. Maybe I just don't understand it. However, here's the problem; I got this class:
import sqlite3
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def saveToDatabase(self):
connection = sqlite3.connect("users.db")
cur = connection.cursor()
cur.execute("DROP TABLE IF EXISTS users")
cur.execute("CREATE TABLE users (name TEXT PRIMARY KEY, age INTEGER)")
cur.execute("INSERT OR REPLACE INTO users VALUES (?,?)", (self.name, self.age))
connection.commit()
connection.close()
#staticmethod
def printUserFromDatabase(name):
connection = sqlite3.connect("users.db")
cur = connection.cursor()
cur.execute("SELECT * FROM users WHERE name=?", name)
print(cur.fetchone())
connection.close()
And it works, database gets created, and I can add users to it, but when ever I try to print an user from database, this happens:
>>> tom = User("Tom", 24)
>>> tom.saveToDatabase()
>>> User.printUserFromDatabase("Tom")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
User.printUserFromDatabase("Tom")
File "C:\Users\Markus\Desktop\foo\foo.py", line 25, in printUserFromDatabase
cur.execute("SELECT * FROM users WHERE name=?", name)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.
>>>
since name is iterable it tries to unpack it ... put it in a tuple with just itself to fix
cur.execute("SELECT * FROM users WHERE name=?", (name,))

Categories

Resources