Sqlite3 Change position column (reordering) - python

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?

Related

how to insert dataframe into sql workbench. on local host

# Create the connection object
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "umar1234",
database="date_sheet"
)
# print(mydb)
# # To Create Database
mycursor = mydb.cursor()
# creating column list for insertion#BSIT(M)-VII
print(data.columns.tolist())
cols = "`,`".join([str(i) for i in data])
for i,row in data.iterrows():
sql = "INSERT INTO `room` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
# cursor.execute(sql, tuple(row))
cursor.execute()
connection.commit()
i want to insert data frame into sql workbench ...
database name ,and username and password is mentioned..
but i got an error..
Traceback (most recent call last):
File "C:\Users\UMAR\PycharmProjects\FYP\scend.py", line 36, in <module>
cursor.execute()
AttributeError: module 'mysql.connector.cursor' has no attribute 'execute'

How to pass multiple variables as values in second sqlite execute argument

I have a database, and I wish to add multiple values to the same row. I am somewhat new with sqlite and databases, but I am learning. I know I can do this:
conn = sqlite3.connect('sqlitedb.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS threadTable(threadName varchar(30)')
c.execute('INSERT INTO threadTable (threadName) Values(?), x.Name')
This works for me, but I want to pass Multiple variables into the table, like so:
conn = sqlite3.connect('sqlitedb.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS threadTable(threadName varchar(30),threadKey varchar(10),threadID varchar(1000))')
c.execute('INSERT INTO threadTable (threadName),(threadKey),(threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))
When I try this, I get this error:
Traceback (most recent call last):
File "Files/main.py", line 39, in <module>
c.execute('INSERT INTO threadTable (threadName),(threadKey),(threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))
sqlite3.OperationalError: near ",": syntax error
you don't need parantheses around each column :
c.execute('INSERT INTO threadTable (threadName,threadKey,threadID) VALUES(?,?,?)', (x.Name, x.Key, x.ID))

sqlite3 database query in 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.

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)

opening and closing mysql connection

I have this python function:
import MySQLdb as mdb
def sql_query(sql):
try:
con = mdb.connect('localhost', 'user', '', 'dbs')
with con:
cur = con.cursor()
cur.execute(sql)
results = cur.fetchall()
return results
except mdb.Error, e:
sys.exit(1)
finally:
if con:
con.close()
then i have loads of code that calls this function, sometime the con closes and i get this traceback:
Traceback (most recent call last):
File "users.py", line 431, in <module>
orders = get_orders(user_id, mongo_user_id, address_book_list)
File "users.py", line 343, in get_orders
order_lines = get_order_lines(order_id)
File "users.py", line 288, in get_order_lines
for item in sql_query(get_order_lines_sql):
File "users.py", line 57, in sql_query
if con:
UnboundLocalError: local variable 'con' referenced before assignment
where my get_orders code is like:
def get_orders(user_id, mongo_user_id, address_book_list):
# we just want orders that are less than 2 years old
get_orders_sql = """SELECT order_id, state, state2, stamp, reference, comments, address_id, delivery_id, user_id FROM user_orders WHERE address_id IS NOT NULL and stamp >= '2012-01-01 00:00:00' and user_id='%s' ORDER BY stamp DESC"""% (user_id)
# delivery_id - this is the shipping option the user chose.
for items in sql_query(get_orders_sql):
#print items
order_id = items[0]
there is about 50K rows in the orders
any advice much appreciated
you need to initialize con since let say there was error in mdb.connect your get error when it some how reaches final your con is still un initialized
import MySQLdb as mdb
def sql_query(sql):
con='' #this should be intiated
try:
con = mdb.connect('localhost', 'user', '', 'dbs')
with con:
cur = con.cursor()
cur.execute(sql)
results = cur.fetchall()
return results
except mdb.Error, e:
sys.exit(1)
finally:
if con:
con.close()

Categories

Resources