Why is named parameter 'not defined'? - python-3.x

Trying to use a named parameter in a simple sql query. Upon assigning a value to the parameter, the marameter name is flagged as undefined (NameError)
Same query works fine with positional parameter
Tried over different tables with different parameter names
Passed values directly rather than via variables
import sqlite3
myConn = sqlite3.connect("testDB.db")
myCursor = myConn.cursor()
myCursor.execute(
"SELECT CourseName FROM Courses WHERE CourseName =:course",{'English':course})
print(myCursor.fetchone())
I should retrieve just the one line from the db.
instead I get the following error message
line 14, in <module>
myCursor.execute("SELECT CourseName FROM Courses WHERE CourseName =:course",{'English':course})
NameError: name 'course' is not defined

The secon argument ot the execute query is a dictionary. The key is the named parameter used in the SQL query (it needs too be in btw quotes) the value for that key is a variable instantiaded somewhere else in the code.
import sqlite3
myConn = sqlite3.connect("testDB.db")
myCursor = myConn.cursor()
query = "SELECT CourseName FROM Courses WHERE CourseName=:course"
test = "English"
myCursor.execute("SELECT CourseName FROM Courses WHERE CourseName =:course",{'course':test})
print(myCursor.fetchone())

Related

PartiQL INSERT Statement to append a Value to a List Attribute

I am trying to append a Value to an existing List Attribute in DynamoDB using PartiQL Syntax.
The Primary Key of the Item consists of:
pk = userId
sk = happeningId
table_name = test_table
userId = "user09hfh47egd53tgd"
happeningId = "happ09hdg2536dget7354tdg"
contactId = "C0003"
decision = "accept"
if decision == "accept":
stmt = f"UPDATE \"{table_name}\" SET accept = list_append(accept, :'{contactId}') WHERE pk='{userId}' AND sk='{happeningId}'"
print(stmt)
resp = dynamodb_client.execute_statement( Statement=stmt )
else:
stmt = f"UPDATE \"{table_name}\" SET cancel = list_append(cancel, :'{contactId}') WHERE pk='{userId}' AND sk='{happeningId}'"
print(stmt)
resp = dynamodb_client.execute_statement( Statement=stmt )
The final string looks like this
UPDATE "test_table" SET accept = list_append(accept, :'C0003') WHERE pk='user09hfh47egd53tgd' AND sk='happ09hdg2536dget7354tdg'
When i try to run my code i get the following error message:
ClientError: An error occurred (ValidationException) when calling the ExecuteStatement operation: Statement wasn't well formed, can't be processed: Unexpected term
Anyone has an idea what i am doing wrong?
Try to write your Statement like that:
contactId = ["C0003"]
stmt = f"UPDATE \"{table_name}\" SET accept = list_append(accept, {contactId}) WHERE pk='{userId}' AND sk='{happeningId}'"
Explanation:
The Value that you want to append to your List, needs to come in a List Type as well. Furthermore the doublepoint was not necessary and the quotes in '{contactId}' need to be removed because they transform the inserted value into a string. And as i said, the Value needs to be as List Type as well.
Hope that helps.

Trying to extract data through bind variables in cx_oracle python

I am trying execute below block of code with cx_oracle by bind variables, but getting below mentioned error everytime. Not sure what is missing.
Anyone has idea on this
Code :
a = input("Please enter your name ::")
conn = cx_Oracle.connect('hello/123#oracle')
cur = conn.cursor()
text1 = "select customer from visitors where name = :myvalue;"
cur.execute(text1,myvalue=str(a))
ERROR observed :
cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended
Remove the semi-colon at the end of your SQL statement.

Python PYODBC INSERT - Too Few Parameters

I've been over this multiple times, I've taken a copy of the database file for testing purposes and even renamed the field to match the Python script. So the field name I am using in Python matches the tables field name exactly.
import pyodbc
def main():
tble="SomeTable"
fld1="SomeField"
val1="TestValue"
sqlStrng = """INSERT INTO %s (%s) VALUES(%s);""" %(tble, fld1,val1)
contStrng = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=Some\Path\File.accdb;'
)
cnnctn = pyodbc.connect(contStrng)
cursr = cnnct.cursor()
cursr.execute(sqlStrng)
cnnctn.commit()
cnnctn.close()
This isn't a spelling issue. I've made a testing copy of the Access file and created a table called SomeTable with a field called SomeField. I have the correct path, I've verified this by running a SELECT SQL script, which works without issue.
I've tried making fld1 a parameter and then sending that with the execute command, but then I'm informed I need 0 parameters. When I remove it, I'm informed I need 1.
I'm beginning to think perhaps it's this file? The same code works on another file I have. However I created a brand new file, and same results. I have to be missing something.
If you print(sqlStrng) immediately after assigning it you'll see that its value is
INSERT INTO SomeTable (SomeField) VALUES(TestValue);
The Access Database Engine treats unrecognized names as parameters, so it wants to be given a parameter value for name TestValue. If you want to insert the string value 'TestValue' then you should use a pyodbc parameter placeholder (?) and pass val1 as a parameter in the .execute method, like so:
tble="SomeTable"
fld1="SomeField"
val1="TestValue"
sqlStrng = """INSERT INTO [%s] ([%s]) VALUES(?);""" %(tble, fld1)
contStrng = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=Some\Path\File.accdb;'
)
cnnctn = pyodbc.connect(contStrng)
cursr = cnnct.cursor()
cursr.execute(sqlStrng, val1)
Notice that you wouldn't get an error if SomeField was a Number field and you used val1=123 because 123 would be treated as a numeric literal, not an unrecognized name (unquoted text value).

Substituting Variables Value in Mongodb statement

My main intention is to dynamically change the Employees collection while using pymongo, and i was able to do it for insert commands, I am facing problems with the find command, no matter what i do exec() always returns None. but if i copy the string and run it value gets assigned to the variable.
can someone throw some light on why the exec is unable to return a resultset or assign a the resultset to a variable?
db.Employees.update_one(
{"id": criteria},
{
"$set": {
"name":name,
"age":age,
"country":country
}
}
)
from pymongo import MongoClient
import ast
client = MongoClient('localhost:27017')
db = client.TextClassifier
insert works
def mongo_insert_one(COLLECTION_NAME, JSON):
QUERY = """db.%(COLLECTION_NAME)s.insert_one( %(JSON)s )""" % locals();
exec(QUERY)
def mongo_retrive(COLLECTION_NAME, JSON):
resultset = None
query = """resultset = db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();
return resultset
print(mongo_retrive('hungry_intent', "{'Intent':'Hungry'}"))
neither this would work
resultset = exec(""" db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();)
this would not work for an entirely different reason,it says If you meant to call the 'locals' method on a 'Database' object it is failing because no such method exists.
resultset = db.locals()[COLLECTION_NAME].find()
PyMongo Database objects support bracket notation to access a named collection, and PyMongo's included bson module provides a much better JSON decoder than "eval":
from bson import json_util
COLLECTION_NAME = 'hungry_intent'
JSON = "{'Intent':'Hungry'}"
print(list(db[COLLECTION_NAME].find(json_util.loads(JSON))))
This will be faster and more reliable than your "eval" code, and also prevents the injection attack that your "eval" code is vulnerable to.
If you can avoid using JSON at all it could be preferable:
COLLECTION_NAME = 'hungry_intent'
QUERY = {'Intent':'Hungry'}
print(list(db[COLLECTION_NAME].find(QUERY)))

How to get Id from Object in Odoo 10?

This is my structure:
class Imprint_Location(models.Model):
_name = 'imprint.location'
name = fields.Char()
product_id = fields.Many2one('product.template')
class Imprint_Charges(models.Model):
_name = 'imprint.charge'
_rec_name = 'location_id'
product_id_c = fields.Many2one('product.template', required=True)
location_id = fields.Many2one('imprint.location', required=True)
#api.multi
#api.onchange('product_id_c', 'location_id')
def product_filter(self):
res = {}
print '\n\n-------\n\n', self, self.product_id_c, '\n\n-------\n\n'
if self.product_id_c:
res['domain'] = {'location_id': [('product_id', '=', self.product_id_c.id)]}
print res
return res
class Product_Template(models.Model):
_inherit = 'product.template'
imprint_location_ids = fields.One2many('imprint.location', 'product_id')
sale_imprint_charge_ids = fields.One2many('imprint.charge', 'product_id_c')
Now i have defined a page in product.template and inside the page is sale_imprint_charge_ids which is in <tree editable="bottom"> and i am not selecting the product_id_c field[also this field doesn't show up in the tree defined].
Now my problem here is that when i select this from the form view which i defined for imprint.charge the method product_filter works fine, but when i enter from the product.template then i get a error saying
TypeError: <odoo.models.NewId object at 0x7fbb8bc21b90> is not JSON serializable
Because from product.template if passes the object <odoo.models.NewId object at 0x7fbb8bc21b90> , so if print self.product_id_c then it prints product.template(<odoo.models.NewId object at 0x7fbb8bc21b90>) so this is not serializable. i have tried doing self.product_id_c.ids which give output empty list [].
So how do get the product.template id from the object or pass the id itself overriding some method.
You should improve couple of following points.
res['domain'] = {'location_id': [('product_id', '=', self.product_id_c.id)]}
return res
study some search() method of ORM
Try with following code:
#api.multi
#api.onchange('product_id_c', 'location_id')
def product_filter(self):
res = {}
if self.product_id_c:
self.location_id = False
#search product_template in imprint.locationwith table and limit we will get only record if related record found
location_id = self.env['imprint.location'].search([('product_id', '=', self.product_id_c.id)], limit=1)
if location_id:
#location_id.ids will give you something like [2] so we need to set value as 2
self.location_id = location_id.ids[0]
EDIT:
As per your first comment, you need a list of related location then we should following trick.
Remove product_filter() method
Add domain in imprint.charge object view file
For example:
<field name="location_id" domain="[('product_id', '=', product_id_c)]"/>
Afterwards, Restart Odoo server and upgrade your custom module.
When creating a brand new record Odoo creates that wierd <odoo.models.NewId object at 0x7fbb8bc21b90> object. After you have written the record this id gets turned into the normal ids that you are used to (an integer). In this situation you have a function which (not unreasonably) expects a real id value at a point when no such value really exists. You need to provide a fallback, such as evaluating if the id is an integer and providing an alternate value in that circumstance. Although your function seems to return an object which I dont quite know what you are expecting to happen. If you wish to modify the value of one of your fields I would modify the values of the self object rather that returning an object.

Resources