I get an error when changing data in SQlite; Python - python

I'm trying to save new data in sqlite and get an error.
Code:
def saveChanges(player_to_save, player_id):
db = sqlite3.connect('db_player.db')
sql = db.cursor()
sql.execute(f"""UPDATE users SET (lvl = {player_to_save.lvl}, exp = {player_to_save.exp}, hp = {player_to_save.hp}, items = {converToJson_items(player_to_save)}, weapon = {convertToJson_weapon(player_to_save)}, armour = {convertToJson_armour(player_to_save)}, bounus = {convertToJson_bounus(player_to_save)}, bonuses_award = {convertToJson_bonuses_award(player_to_save)}, stats = {converToJson_stats(player_to_save)} ) WHERE login = '{player_id}'""")
Error:
line 384, in saveChanges
sql.execute(f"""UPDATE users SET (lvl = {player_to_save.lvl}, exp = {player_to_save.exp}, hp = {player_to_save.hp}, items = {converToJson_items(player_to_save)}, weapon = {convertToJson_weapon(player_to_save)}, armour = {convertToJson_armour(player_to_save)}, bounus = {convertToJson_bounus(player_to_save)}, bonuses_award = {convertToJson_bonuses_award(player_to_save)}, stats = {converToJson_stats(player_to_save)} ) WHERE login = '{player_id}'""")
sqlite3.OperationalError: near "=": syntax error
How can i fix it?

Use this syntax-
sql.execute('''UPDATE tablename SET v1 = ?, v2 = ? where c1 = ?;''', (new_val1, new_val2, condition))

Related

Incorrect number of bindings supplied. The current statement uses 1, and there are 6 supplied

In the line:
for row in cursor.execute("SELECT classCapacity FROM tblClass1 WHERE classID = ?", [classID]):
I am getting a binding error saying the statement uses one and six have been supplied and have been stuck trying to fix it for hours now any suggestions are welcome.
def addBooking():
def CostCalculation():
Cost = 0
Validation = False
sqlite3.connect("TestProject.db")
cursor = connection.cursor()
for row in cursor.execute("SELECT classCost from tblClass1 WHERE classID =?", cClassID):
Validation = True
cost = row[0]
Cost = (int(cost))
return Cost, Validation
connection = sqlite3.connect("TestProject.db")
curosr = connection.cursor()
cClientID = getID(clientID.get())
cClassID = classID.get()
cDate = bookingDate.get()
cCost, costValidation = CostCalculation()
bookingRec = [cClientID, cClassID, cDate, cCost]
for row in cursor.execute("SELECT classCapacity FROM tblClass1 WHERE classID = ?", [classID]):
maxCap = row[0]
capacity = 0
for row in cursor.execute("SELECT * FROM tblBooking WHERE classID = ? and bookingDate =?", [cClassID, cDate]):
capacity = capacity + 1
if capacity < maxCap:
cursor.execute("INSERT INTO tblBooking VALUES(Null,?,?,?,?)", bookingRec)
connection.commit()
connection.close()

Python query wrong output

I had a query that should return all permittedUserId when userId matched with what was supplied my the user. I wanted to use the result of the query for a different query and noticed I kept getting the same output.
sql = "SELECT permittedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
Here is what the table looks like
Why do I get this output?
[{'num': 3}, {'num': 3}, {'num': 3}, {'num': 3}]
The output I want should be number 7,6,2,3, not 3,3,3,3
Here's the whole code:
self.ensureConnected()
applicationUser = (content['userID'], )
sql = "SELECT permitedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
crows = self.cursor.execute(sql, applicationUser)
result = self.cursor.fetchall()
if(len(result) > 0 ):
d = collections.OrderedDict()
objects_list = []
for row in result:
d['num'] = row[0]
#sqlname = "SELECT name , username FROM Users WHERE Users.id=%s"
#valname = (row[0],)
#self.cursor.execute(sqlname,valname)
#resultName = self.cursor.fetchall()
#for row2 in resultName:
# d['name'] = row2[0]
# d['username'] = row2[1]
objects_list.append(d)
return (json.dumps(dict(data = objects_list), default=str), 200)
elif(crows ==None):
return (json.dumps(dict(data = "empty")), 200)
Here's a sample table which I created in SQL
and the code to fetch the data from it
import mysql.connector
db = mysql.connector.connect(host='localhost',user='root',passwd='5548',database='test')
cursor =db.cursor()
n='1'
cursor.execute("select permission from test where userid = %s",(n,))
v = cursor.fetchall()
for i in v:
print(i[0],end=" ")
and the output is
7 6 2 4
Hence, the way you are establishing the connection and retrieving the data is fine.
Looking at the for loop - I can see the probable error
objects_list.append(d)
should be
objects_list.append(d['num'])
The code should look like this
applicationUser = (content['userID'], )
sql = "SELECT permitedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
crows = self.cursor.execute(sql, applicationUser)
result = self.cursor.fetchall()
if(len(result) > 0 ):
d = collections.OrderedDict()
objects_list = []
for row in result:
d['num'] = row[0]
#sqlname = "SELECT name , username FROM Users WHERE Users.id=%s"
#valname = (row[0],)
#self.cursor.execute(sqlname,valname)
#resultName = self.cursor.fetchall()
#for row2 in resultName:
# d['name'] = row2[0]
# d['username'] = row2[1]
objects_list.append(d['num'])

How to use multiple variables in pymysql

How can I use multiple variables in my query:
import pymysql
def get_firstname(y):
db = pymysql.connect(host="xxx.xxx.xxx.xxx",
user="xxxx",
passwd="xxxxx",
db="XXXXXXX")
cur = db.cursor()
query = "SELECT first_name FROM information WHERE x = y;"
cur.execute(query, (y))
result = str(cur.fetchone()[0])
return(result)
x = user_id
y = 1
print (get_firstname(y))
I would like to be able to change x to different variables, depending on my choice. Like user_id, last name, email etc. All columns in my database. #y is another variable which represent the value of the column in my database.
Ex1: if x is "user_id" and y is "1", then the result is the first name of the person with user_id 1.
Ex2: if x is "email" and y is "person#person.com", then the result is the first name of the person with the email person#person.com.
Use the below code:
import pymysql
def get_firstname(x, y):
db = pymysql.connect(host='xxx.xxx.xxx.xxx',
port=3306,
user='xxxx',
password='xxxxxxxx',
db='test_db')
cur = db.cursor()
query = "SELECT first_name FROM `information` WHERE %s" %(x)
final_query = query+"=%s"
#print(final_query)
cur.execute(final_query, (y,))
result = cur.fetchall()
return(result)
x = 'user_id'
y = 1
output = get_firstname(x,y)
if output:
for x in output:
print(x)[0]
Sample Inputs:
x = 'email_id'
y = 'xx#gmail.com'
or
x = 'user_id'
y = 1 // Not enclosed with single quotes

UnboundLocalError: local variable 'Core_prices' referenced before assignment

i use a function calculate servers prices so i made a function which retrieve a defalut prices of a server components and calculate server price for each server exsit in my DB but i try to run this function, i get this error:
function.py
import MySQLdb
def calculations_metric (param) :
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM examples_calculationsmetric"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
RAM_prices = int(row[1])
Core_prices = int(row[2])
HHD_SATA_prices =int(row[3])
HHD_SSD_prices =int(row[4])
CPU_priority = int(row[5])
Avaibility = int(row[6])
db.close()
db1 = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor1 = db1.cursor()
sql1 = "SELECT * FROM examples_servercomponents WHERE id ='%d'" %(param)
cursor1.execute(sql1)
results1 = cursor1.fetchall()
for row in results1:
if row[6] == 'SATA':
Core_price = int(row[2]) * Core_prices # the error is here
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SATA_prices
Availibility_price = int(row[7])*Avaibility
elif row[6] == 'SSD':
Core_price = int(row[2]) * Core_prices
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SSD_prices
Availibility_price = int(row[7])*Avaibility
price = Core_price + Priority_price + RAM_price + HDD_price + Availibility_price
db1.close()
return price
i don't get what is the error so if can anyone help i will be so greatful
When your SELECT * FROM examples_calculationsmetric doesn't return any results, Core_prices is never set (nor are the other variables in that loop).
Python names do not exist until assigned to, so if results is an empty list, the names inside the for loop never get assigned to and thus do not exist by the time you loop over results1 later on.
You could set default values for those names as a work-around:
RAM_prices = 0
Core_prices = 0
HHD_SATA_prices = 0
HHD_SSD_prices = 0
CPU_priority = 0
Avaibility = 0
to at least ensure that they are defined.

Get data into sqlite from yahoo finance

I trying to get yahoo prices into sqlite...
I have the code below, but cant get the data into ipull []
then into sqlite...
from urllib import urlopen
import win32com.client as win32
import sqlite3
RANGE = range(3, 8)
COLS = ('TICKER', 'PRICE', 'Vol')
URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1v'
TICKS = ('GGP', 'JPM', 'AIG', 'AMZN')
ipull =[]
def excel():
app = 'Excel'
xl = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xl.Visible = True
for x in range(3):
sh.Cells(5, x+1).Value = COLS[x]
row = 6
u = urlopen(URL % ','.join(TICKS))
for data in u:
tick, price, per = data.split(',')
sh.Cells(row, 1).Value = eval(tick)
sh.Cells(row, 2).Value = ('%.2f' % float(price))
sh.Cells(row, 3).Value = eval(per.rstrip())
row += 1
u.close()
con = sqlite3.connect('/py/data/db2')
c = con.cursor()
c.execute('INSERT INTO prices VALUES (?,?,?)', ipull)
con.commit()
c.close()
if __name__=='__main__':
excel()
You declare ipull[], but never assign it.

Categories

Resources