How to determine the row id from a column field - SQLite 3, Python - python-3.x

In my SQLite database I have a table called client_dir that is a directory of client contact details. I also have a table called contracts that contains the details of different contracts. I need to be able to create foreign keys that bind a contract entry to a client entry in client_dir.
The thing is , I want to be able to generate the foreign key by just providing the clients name. How do I summon the row id from a field entry?
I think it should look something like this...
def new_contract():
'''creates a new contract entry and links it to a client in the client_dir table'''
client = input("Company name...")
#int(row_id) = client
contract = input("New contract...")
self.cursor.execute("INSERT INTO contracts VALUES (?)",contract,#row_id)
UPDATE
My tables look like this :
self.cursor.execute("""CREATE TABLE client_dir(cli_id INTEGER PRIMARY KEY AUTOINCREMENT, company TEXT, address TEXT, phone INTEGER, email TEXT)""")
self.cursor.execute("""CREATE TABLE contracts(con_id INTEGER PRIMARY KEY AUTOINCREMENT, contract TEXT, client_id INTEGER, FOREIGN KEY(client_id) REFERENCES client_dir(cli_id))""")
and my new _contract method looks like this:
def new_contract(self):
'''creates a new contract entry and links it to a client in the client_dir table'''
client = input("Company name...")
for f_list in self.cursor.execute("SELECT cli_id FROM client_dir WHERE company = (?)",[client]):
f_key = f_list[0]
print(f_key) # For debugging
contract = input("New contract...")
self.cursor.execute("INSERT INTO contracts VALUES (NULL,?,?)",([contract],[f_key]))
print(f_key) is printing a nice tidy 1 on the screen which I am presuming is an int. but I am getting this error:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
c.new_contract()
File "C:\Python33\smalltime\Client.py", line 63, in new_contract
self.cursor.execute("INSERT INTO contracts VALUES (NULL,?,?)",([contract],[f_key]))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

I have fixed this now. The error was due to the fact I was passing in the wrong syntax for the INSERT.
The correct last line of the new_contract method should be:
self.cursor.execute("INSERT INTO contracts VALUES (NULL,?,?)",**([contract,f_key]))**
(previously it had two extra braces : ([contract],[f_key]) and that was throwing it out)
so all that remains to do is remove the print statement and add
self.conn.commit()
to the end.

Related

Hybris ImpEx - how to export all Orders, which contain a specific coupon code

I want to export all items of type Order, which contain a coupon code named 'TESTCOUPON'. However, when I try to do it, I get this error:
ERROR line 4 at main script: error executing code line at 4 : SQL search error - ORA-00932: inconsistent datatypes: expected - got BLOB
query = 'SELECT item_t0.PK FROM orders item_t0 WHERE ( item_t0.p_appliedcouponcodes = 'TESTCOUPON') AND (item_t0.TypePkString IN (?,?,?) )', values = [8796099149906, 8796099215442, 8796098756690]
I assume from the error that the coupon is stored in a Collection/List - how would I filter by it in this case?
The FlexibleSearch line looks like this:
SELECT {C:PK} FROM {Order as C} WHERE {C:appliedCouponCodes} = 'TESTCOUPON'
I tried using the PK of the coupon code, but it doesn't work either and it presents the same error. I tried using LIKE '%TESTCOUPON%' but then it said 'expected CHAR got BLOB'.
As per the Table structure CouponRedemption having reference of Order
.
so correct query will be as below.
select { o.code },{o.pk},{cr.couponCode} from {Order as o Join CouponRedemption as cr on {cr.order}={o.pk}} where {code}='TESTCOUPON'
Output:
code PK p_couponcode
1050156308 9499773075501 BUY4
1044303645 9499775172653 BUY4
1042057811 9499796897837 BUY4
1049853832 9499798863917 BUY4

loc not functioning correctly in pandas

I have a Dataframe, which has a bunch of ID name pairs in it. I create it by doing the following:
market_df = pd.DataFrame(markets_info['markets'])
market_df.astype(dict(id=int, name=str))
I received ID numbers from a process and I need to grab the associated name to that ID. I have tried creating an index on the ID and then parsing it, but that doesn't seem to set the ID correctly.
I now am trying to do the following: exch_name = MARKET_IDS.loc[MARKET_IDS['id'] == exchange_id, 'name']
I have verified that exchange_id is also of type int.
What am I missing here?
I don't know if this is because you left out some crucial information from this, but from what it sounds like in your post you're not really altering market_df at all, as your second line is not an assignment. It should read market_df = market_df.astype(dict(id=int, name=str))

one2many field stores only last record when fill

please help me regarding one2many field in odoo12.
firstly, sorry for bad grammar.
i am getting products from invoice_line_ids of account.invoice model.
but when i store these products in my custom model only last record is stored in one2many field in my class.
here is my code.
invoice_report = self.create(vals)
product_dict={}
product_list=[]
for line in ids.invoice_line_ids:
product_dict.update({
'product_name':line.product_id.name,
'qty':line.quantity,
'unit_price':line.price_unit,
'tax':line.invoice_line_tax_ids.name or "",
'subtotal':line.price_subtotal
})
product_list.append([(1,invoice_report.id,product_dict)])
for data in product_list:
invoice_report.write({
'inv_products':data
})
inv_products is my one2many field
invoice_report is my recently created record. i.e custom.invoice(1,)
According to the x2many values filling, the format you used updates an existing record of id id with the values in values. id should be an id of an inv_products record, not a custom.invoice record.
You should receive an Odoo server error in case record with id equal to 1 does not exist in the database:
One of the records you are trying to modify has already been deleted (Document type: custom.report.line).
(Records: (1,), User: 2)
You declared product_dict outside a for loop and you used update inside, at the end of the loop you will have the values of the last line of invoice_line_ids repeated, You asked the system to update a specific line (with id invoice_report.id) with the same values in each iteration when you called write method.
To add new records to inv_products, use [(0, 0, values)] format:
invoice_report = self.create(vals)
product_list = []
for line in ids.invoice_line_ids:
product_dict = {
}
product_list.append((0, 0, product_dict))
invoice_report.write({
'inv_products': product_list
})

python3 psycopg SQL identifier must be string

I am trying to reference dynamic tables and fields in a tkinter GUI project using MySQLdb. Using psycopg2.sql to handle an insert statement.
The user select a code, size and color and inputs a quantity. The table names are made up of the size and the code (eg. size-small and code-1111, table_name=small1111). Then the color is the column name and the quantity is an integer entered into the field. The inputs are saved in a dictionary (tdict) when the user selects them. And the dictionary elements are called to be saved in the database table.
table_name = tdict['Size']+tdict['Code']
stmnt = ("INSERT INTO {} (%s, Date) VALUES(%s, %s)").format(sql.Identifier((table_name, tdict['Color'])))
c.execute(sql.SQL(stmnt, (tdict['Quantity'], date)))
The insert query is giving me a TypeError
TypeError("SQL identifiers must be strings")
Can anyone please help? What am I doing wrong? How should the Identifier be made to behave as a string?
Note: I've tried to pass the Identifier elements through a str class but it didn't work. ie
stmnt = ("INSERT INTO {} (%s, Date) VALUES(%s, %s)").format(sql.Identifier((str(table_name, tdict['Color']))))
You are asking sql.Identifier() to create an identifier out of a tuple, e.g. ('small1111','magenta'). Because format() only substitutes into braces {} (and not %s), I think what you actually had in mind was this:
stmnt = sql.SQL("INSERT INTO {} ({}, Date) VALUES(%s %s)").format( sql.Identifier(table_name), sql.Identifier(tdict['Color']) )
I'd suggest you rethink your database design, though --- you should probably have columns named size, code, and color rather than separate tables and columns for each. That will prevent you from having to add a new column each time a new color or a new table for each new size or code. SELECT count(*) FROM inventory WHERE size = 'small' AND code = '1111' GROUP BY color seems preferable to having to create queries dynamically.
This error message will also appear when you have a typo error where you should have used sql.Literal('someFixedNumber'), but instead using sq.Identifier('someFixedNumber')

Inserting data into database with python/sqlite3 by recognising the column name

I've got a problem that I don't know how to solve, I've tried many solutions but always getting that Operational error: near...
def insert_medicine_to_table():
con = sqlite3.connect('med_db3.db')
cur = con.cursor()
table_name = 'medicines'
column_name = "présentation"
value = 'Boîte de 2 seringues pré-remplies'
cur.execute("INSERT INTO medicines {} VALUES (?)".format(column_name), value)
con.commit()
con.close()
sqlite3.OperationalError: near "présentation": syntax error
The goal here is that either the script or python has to recognize the field (column name) and insert the value into "that" field, like the following:
fields = ['présentation', 'princeps', 'distributeur_ou_fabriquant', 'composition', 'famille', 'code_atc', 'ppv', 'prix_hospitalier', 'remboursement', 'base_de_remboursement__ppv', 'nature_du_produit']
values = ['Boîte de 2 seringues pré-remplies', 'Oui', 'SANOFI', 'Héparine', 'Anticoagulant héparinique', 'B01AB01', '43.80', '27.40', 'Oui', '43.80', 'Médicament']
That is one entry in the database. The problem here is that other entries can or not have one or more values for some field, and also the fields are not presented in the same order in other entries.
It has to recognize each field in the database table and insert each value into the right column.
The problem causing your error is that your SQL isn't valid. The statement you are trying to execute is:
INSERT INTO medicines présentation VALUES (?)
The statement you want to execute is:
INSERT INTO medicines ("présentation") VALUES (?)
As far as your larger question is concerned, if you create both the list of columns ("présentation") and list of parameter markers (?) and build the query using them, you're most of the way there.
If a field can have multiple values supplied for each "entry" in your database, you may need to change your database design to handle that. You'll at least need to figure out how you want to handle the situation, but that would be a matter for a different question.

Resources