User input not reflected in database (xampp) - python-3.x

In my program, I am getting the user input from combobox and inserting it to database. All values except 'classname' is getting reflected.Its value is shown as zero in the database. I am able to print all the values to be inserted before performing the SQL query.
This the function I executed.
def insert_staff():
id = entry_staffid.get()
subject = subject_combobox.get()
class_name = class_combobox.get()
class_time = timings_combobox.get()
print(id,subject,class_name,class_time)
staff = mysql.connector.connect(host="localhost", user="root", password="", database="school_database")
cursor_variable = staff.cursor()
query = "INSERT INTO staff_schedule(staff_id, subject_allotted, class_name, time_allotted) VALUES ('"+id+"','"+subject+"','"+ class_name +"','"+class_time+"')"
cursor_variable.execute(query)
staff.commit()
staff.close()
Can anyone tell why the value of 'classname' alone is not getting reflected?
Any help is greatly appreciated.

Initially I put the data type of class_name as INT but I was actually using VARCHAR values. This is the reason why the database reflected zero.

Related

exiting lot_id in stock.move.line, showing same value from compute field

I got some issue that lot_name is not showing same value from another compute field in same recordset, stock.move.line. below is my code:
class StockMoveLine(models.Model):
_name = 'stock.move.line'
_inherit = 'stock.move.line'
lotter = fields.Char(string="Supplier Lot", compute='_compute_partner')
def _compute_partner(self):
if not self.lotter:
partner_id = self.env['stock.picking'].search([('name','=',self.reference)]).partner_id.id
self.lotter = str(partner_id)
if self.lot_name == "":
self.lot_name = self.lotter
else:
self.lot_name = "blank"
the lot_name had been already existed in base module field. So I would like to show partner_id in lot_name field as well. now I only see it in my new compute fieldl. I tried using #api.onchange but it is only work when the textfield of lotter is lost focus. how can I do to show the same value on both lotter and lot_name fields if there is no value earlier?
Add store=True in your field.Because compute field is not stored in your database.
lotter = fields.Char(string="Supplier Lot", compute='_compute_partner', store=True)

UPSERT syntax error linked to UPDATE in PostgreSQL (python)

I'm still learning PostgreSQL. During my testing, I have only been using INSERT statement in either psycopg2 and now asyncpg. I now have the need to UPDATE data in my test database, instead of replacing all of it.
I'm currently trying to do a simple replacement test in a testing table, before I move to development table with more data.
I want to replace any $1 name that is in CONFLICT with a name that is already in the table users. I'm trying the query code, which is passed to the DB via asyncpg. I keep getting a syntax errors, so I'm a little lost on how to correct these errors.
What is the proper syntax for this query?
'''INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE "users"
SET name = 'TEST'
WHERE name = excluded.name '''
UPDATE:
I'm getting this error message when using asyncpg:
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near ""users""
I'm getting this error message when using psycopg2:
psycopg2.ProgrammingError: syntax error at or near ""users""
This is the asyncpg code that I have been using to do the INSERTs:
async def insert_new_records(self, sql_command, data):
print (sql_command)
async with asyncpg.create_pool(**DB_CONN_INFO, command_timeout=60) as pool:
async with pool.acquire() as conn:
try:
stmt = await conn.prepare(sql_command)
async with conn.transaction():
for value in data:
async for item in stmt.cursor(*value):
pass
finally:
await pool.release(conn)
test_sql_command = '''
INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE "users"
SET name = 'TEST'
WHERE name = excluded.name '''
# The name 'HELLO WORLD' exists in the table, but the other name does not.
params = [('HELLO WORLD', datetime.date(1984, 3, 1)),
('WORLD HELLO', datetime.date(1984, 3, 1))]
loop = asyncio.get_event_loop()
loop.run_until_complete(db.insert_new_records(test_sql_command, params))
You need single quotes around the value for name: SET name='TEST'
The double quotes are for table or column names. In your case, you could just remove the double quotes around users.
After edit:
You should really try your SQL commands in the database console, this has nothing to do with python nor async. It's pure postgresql syntax.
So, the second issue in your query is that you shouldn't specify "users" after UPDATE. It's implied that you're updating the same table. So just DO UPDATE SET... is good.
Then, you'll get column reference "name" is ambiguous. You should write DO UPDATE SET name='TEST'. You already are updating the row where name=excluded.name. I am not 100% clear on what you're trying to do. So if you insert a row once, it's inserted as usual. If you insert it a second time, the name is replaced with 'TEST'. The excluded keyword allows you to access the attempted insert values. So for example, if you wanted to update the last_access column when trying to insert an existing name, you would write ON CONFLICT (name) DO UPDATE last_access=excluded.last_access.
you can test
replace :
'''INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE "users"
SET name = 'TEST'
WHERE name = excluded.name '''
by :
"""INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE
SET name = 'TEST'
WHERE name = excluded.name """

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.

Removing a column from result set in Groovy Sql rows

I have a query where I need to retrieve a column which I need only temporarily because I need to pass it in the parameter for a where clause, how can I remove this column and its value from my result set after it served that purpose. Hopefully the code will show what I mean...
def empQuery = "select id, name, address from Employee"
def retObj = [:]
def sql = new Sql(datasource)
retObj = sql.rows(empQuery.toString())
retObj.each {
def addressQuery = "select street from Address where employe_id = ${it['id']}
// at this point I want to remove 'id:n' from the result set hash map aka 'it'
}
Because later on I am displaying that result set on a page for the user, and the ID field is not relevant.
So can you please show the Groovy code to remove a column and its value from the rows data structure returned from sql.rows?
from http://docs.groovy-lang.org/latest/html/api/groovy/sql/GroovyRowResult.html
It looks like you can do something line:
retObj.each { it.remove('id')}
However I haven't tried it....

Resources