Problem Using Variable in Sqlite3 Statement - python

I have a problem with a Python 2.7 project.
I'm trying to set a variable to a value retrieved from an sqlite3 database, but I'm having trouble. Here is my code thus far, and the error I'm receiving. Yes, the connection opens just fine, and the table, columns, and indicated row are there as they should be.
import sqlite3 import Trailcrest
conn = sqlite3.connect('roster.paw')
c = conn.cursor()
def Lantern(AI):
"""Pulls all of the data for the selected user."""
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where index = ?;""", (AI,) ).fetchall()
The error is:
> Traceback (most recent call last):
> File "<pyshell#4>", line 1, in <module> Lantern(1)
> File "C:\Users\user\MousePaw Games\Word4Word\PYM\Glyph.py", line 20,
> in Lantern
> Trailcrest.FireAutoHelp = c.execute("""select fireautohelp from roster where index = ?;""", (AI,)).fetchall()
> OperationalError: near "index": syntax error

As Thomas K mentions in a comment, index is a SQL keyword.
You can either rename that column, or enclose in backticks:
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where `index` = ?;""", (AI,) ).fetchall()

Related

Run code inside a string with python .format

I need to use code saved in a string (tmp_str) inside .format ?
tmp_str="ID='ID_VAR_DICT'"
sql_text="SELECT FIELD FROM TABLE_A WHERE ID = {ID}"
sql_query = sql_text.format(ID='ID_VAR_DICT')
print ('sql_query -->',sql_query) #Print A
sql_query = sql_text.format(eval(tmp_str))
print ('sql_query -->',sql_query) #Print B
Basically I need #Print B to output the same as #Print A but passing the contents off tmp_str to .format
Output:
('sql_query -->', 'SELECT FIELD FROM TABLE_A WHERE ID = ID_VAR_DICT')
Traceback (most recent call last):
File "_testes.py", line 7, in <module>
sql_query = sql_text.format(eval(tmp_str))
File "<string>", line 1
ID='ID_VAR_DICT'
Thanks in advance,
M
This isn't a recommendation -- as chepner says in a comment, you should use a prepared statement with parameters.
But if you really need to do it your way, you have to eval the entire expression, not just the argument.
sql_query = eval(f'sql_text.format({tmp_str})')

Executing python function in postgres

I'm trying to run a python function on the cursor.execute parameter but it just throws me this error.
I'm using psycopg2
Traceback (most recent call last):
File "cliente.py", line 55, in <module>
cursorDB.execute(get_datos_animal('falsa'))
psycopg2.errors.UndefinedColumn: column "falsa" does not exist
LINE 1: ...e, clasificacion FROM animales WHERE animales.hierro = falsa
and my python function is this one
def get_datos_animal(hierro_v):
return "SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion FROM animales WHERE animales.hierro = " + str(hierro_v)
any idea what i´m doing wrong?
Have several functions like this with same errors.
Use the automatic parameter quoting provided by your connection to ensure that values in queries are always quoted correctly, and to avoid SQL injection attacks.
stmt = """SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion
FROM animales
WHERE animales.hierro = %s"""
cursor.execute(stmt, (hierro_v,))
In postgres if you pass value without quotes it will treat that as column name.
Try this:
def get_datos_animal(hierro_v):
return "SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion FROM animales WHERE animales.hierro = '"+str(hierro_v)+"'"

sqlite3.OperationalError: table inventory has no column named car_make. when database has column

i keep getting the error
Traceback (most recent call last):
File "C:\Users\max\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "G:\computing project\add to db.py", line 114, in get_items
C.execute(sql ,vari)
sqlite3.OperationalError: table inventory has no column named car_make
when attempting to insert values into mydatabse taken from tkinter
i have tried changing the names of the columns in order to see if that would solve the issue bit nothing has changed, i am using db browser in order to edit my database
from tkinter import*
import sqlite3
conn = sqlite3.connect("G:\computing project\database of cars.db")
C = conn.cursor()
import tkinter.messagebox
def get_items(self,*args,**kwargs): #this function gets the items from the entry boxes
self.carmake= self.carmake_e.get()
self.carmodel= self.carmodel_e.get()
self.regi= self.regi_e.get()
self.colour= self.colour_e.get()
self.cost= self.cost_e.get()
self.tcost= self.tcost_e.get()
self.sellprice= self.sellprice_e.get()
self.assumedprofit= self.assumedprofit_e.get()
self.assumedprofit= float(self.sellprice)- float(self.tcost)
if self.carmake == '' or self.carmodel == '' == self.colour == '':
print ("WRONG")
tkinter.messagebox.showinfo("error","please enter values for car make, model and colour")
else:
print("solid m8 ")
sql = "INSERT INTO inventory(car_make,car_model,registration_plate,colour,cost,total_cost,selling_price,assumed_profit) VALUES (?,?,?,?,?,?,?)"
vari=(self.carmake,self.carmodel,self.regi,self.colour,self.cost,self.tcost,self.sellprice,self.assumedprofit)
C.execute(sql ,vari)
# C.execute(sql(self.name,self.carmake,self.carmodel,self.regi,self.colour,self.cost,self.tcost,self.sellprice,self.assumedprofit))
conn.commit()
tkinter.messagebox.showinfo("success","succesfully added to databse")

Issue in Model-View-Controller Pattern implementation

I am running an example for learning The Model-View-Controller Pattern in python, but the code is giving an error. I tried to debug the code, but I couldn't find the main root/cause. Removing close connection system works, but what is the issue of the code? Can you advise me what is wrong?
# Filename: mvc.py
import sqlite3
import types
class DefectModel:
def getDefectList(self, component):
query = '''select ID from defects where Component = '%s' ''' %component
defectlist = self._dbselect(query)
list = []
for row in defectlist:
list.append(row[0])
return list
def getSummary(self, id):
query = '''select summary from defects where ID = '%d' ''' % id
summary = self._dbselect(query)
for row in summary:
return row[0]
def _dbselect(self, query):
connection = sqlite3.connect('example.db')
cursorObj = connection.cursor()
results = cursorObj.execute(query)
connection.commit()
cursorObj.close()
return results
class DefectView:
def summary(self, summary, defectid):
print("#### Defect Summary for defect# %d ####\n %s" % (defectid,summary) )
def defectList(self, list, category):
print("#### Defect List for %s ####\n" % category )
for defect in list:
print(defect )
class Controller:
def __init__(self): pass
def getDefectSummary(self, defectid):
model = DefectModel()
view = DefectView()
summary_data = model.getSummary(defectid)
return view.summary(summary_data, defectid)
def getDefectList(self, component):
model = DefectModel()
view = DefectView()
defectlist_data = model.getDefectList(component)
return view.defectList(defectlist_data, component)
This is related run.py.
#run.py
import mvc
controller = mvc.Controller()
# Displaying Summary for defect id # 2
print(controller.getDefectSummary(2))
# Displaying defect list for 'ABC' Component print
controller.getDefectList('ABC')
If you need to create the database, it is available here:
# Filename: datbase.py
import sqlite3
import types
# Create a database in RAM
db = sqlite3.connect('example.db')
# Get a cursor object
cursor = db.cursor()
cursor.execute("drop table defects")
cursor.execute("CREATE TABLE defects(id INTEGER PRIMARY KEY, Component TEXT, Summary TEXT)")
cursor.execute("INSERT INTO defects VALUES (1,'XYZ','File doesn‘t get deleted')")
cursor.execute("INSERT INTO defects VALUES (2,'XYZ','Registry doesn‘t get created')")
cursor.execute("INSERT INTO defects VALUES (3,'ABC','Wrong title gets displayed')")
# Save (commit) the changes
db.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
db.close()
My error is as below:
> Windows PowerShell Copyright (C) Microsoft Corporation. All rights
> reserved.
>
> PS E:\Projects\test> & python e:/Projects/test/mvc.py
> Traceback (most recent call last): File
> "e:/Projects/test/mvc.py", line 56, in <module>
> import mvc File "e:\Projects\test\mvc.py", line 65, in <module>
> cursor.execute("drop table defects") sqlite3.OperationalError: no such table: defects PS E:\Projects\test> & python
> e:/Projects/ramin/mvc.py Traceback (most recent call last):
> File "e:/Projects/test/mvc.py", line 56, in <module>
> import mvc File "e:\Projects\test\mvc.py", line 80, in <module>
> print(controller.getDefectSummary(2)) File "e:\Projects\test\mvc.py", line 44, in getDefectSummary
> summary_data = model.getSummary(defectid) File "e:\Projects\test\mvc.py", line 18, in getSummary
> for row in summary: sqlite3.ProgrammingError: Cannot operate on a closed cursor. PS E:\Projects\test>
I suspect that the problem is this line: cursor.execute("drop table defects")
Maybe you dropped that table in a previous run, and since it's no longer there, sqlite3 raises an OperationalError exception.
In your code there is a comment that says that you are using an in-memory sqlite database, but you are not. This is how you create an in-memory db:
db = sqlite3.connect(:memory:)
If you use an in-memory db you don't need to drop anything, since you are creating the db on the fly when you run your script.
Note: last year I wanted to understand the MVC better, so I wrote a series of articles about it. Here is the one where I use SQLite as a storage backend for my Model.

Python - MySQLdb parametrized query

I'm trying to create a simple script for changing some mysql data, but I'm little bit confused about parametrized queries. The code look like this:
reader_id = sys.argv[1]
cmd_id = sys.argv[2]
conn = mysql.connect(user='...', passwd='...', host='...', db='...')
curs = conn.cursor()
mysql_data = {
"reader_id": int(reader_id),
"cmd_id": int(cmd_id)
}
curs.execute("UPDATE `reader_config_hw` SET `changed_` = '1' "
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
curs.execute("UPDATE `reader` SET `check_for_command` = '1' WHERE `id` = %(reader_id)d", mysql_data)
and the error result is
Traceback (most recent call last):
File "./main.py", line 25, in <module>
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
File "/usr/lib64/python3.6/site-packages/MySQLdb/cursors.py", line 210, in execute
query = query % args
TypeError: %d format: a number is required, not str
It says that number is required but I already changed the type of the variable by int(reader_id), is it right?
Try changing
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
to
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
I think the 'd' after your variable calls indicates a "digit" whereas you need to use a string.
EDIT: to clarify, strings can be used in place of integers in MySQL queries

Categories

Resources