i have create a mysql table like----> create table test(gender char(1));
my python sudo code is---->
from pymysql import *
g='m'
sql='insert into test values(%s)' %g
cur.execute(sql)
con.commit()
con.close()
but its giving me error --->
(1054, "Unknown column 'm' in 'field list'")
plz help me out to solve it
The
'insert into test values(%s)' %g
expands to
'insert into test values(m)'
which is clearly not what you want (what is m?)
My recommendation is to use bind parameters:
g = 'm'
sql = 'insert into test values(?)'
cur.execute(sql, g)
For more information, see How to use variables in SQL statement in Python?
You should try this:
'insert into test () values('%s')' %g
... this is because the variable g is aString` and after the append that you are doing this must look like:
"insert into test () values('m')" and not "insert into test () values(m)"
<>
cheers
Related
I'm getting the following error in console, where the column name actually is the value passed through the query:
pymysql.err.OperationalError: (1054, "Unknown column 'LiqNac83437' in
'where clause'")
This is my function:
sql = f"""
SELECT
detallev.clave,
detallev.cantidad,
venta.fecha
FROM
detallev
INNER JOIN
venta ON detallev.ven_id = venta.ven_id
WHERE
clave = '{codigoBarras}'
AND (fecha BETWEEN {fecha_inicio} AND {fecha_final});"""
print(sql)
with bd:
with bd.cursor() as cursor:
cursor.execute(sql)
resultado = cursor.fetchall()
cursor.close()
which is called by:
#app.get('/{sucursal}/reporte/articulos/')
def reporte_articulo(sucursal: Origenes, clave: str = '', fecha_inicial: str = '', fecha_final: str = fechaHoy(), username: str = Depends(valida_usuario)):
return reporte_articulos.reporte_articulo(sucursal, clave, fecha_inicial, fecha_final)
I'm using FastAPI, python and Mysql.
I've already tried following these solutions with no luck:
Solution 1
Solution 2
and several other solutions outside stackoverflow, already tried wrapping the concatenated value in different type of ways.
When running this query directly on Mysql workbench it works perfect, aside from calling it from the API.
When the column name value passed to the function is only numbers as "47839234215" instead of "LiqNac83437", which is numbers and letters, It works great as expected.
This happens because you are substituting the values yourself, and in this case you have not properly quotes the fields in the BETWEEN clause. It sees LiqNac83437 and thinks it is a column name, because it is not quoted.
For this reason, and to avoid SQL injection problems, you should let the database connector do the quoting:
sql = """
SELECT
detallev.clave,
detallev.cantidad,
venta.fecha
FROM
detallev
INNER JOIN
venta ON detallev.ven_id = venta.ven_id
WHERE
clave = ?
AND fecha BETWEEN ? AND ?;"""
with bd.cursor() as cursor:
cursor.execute(sql, (codigoBarras, fecha_inicio, fecha_final))
resultado = cursor.fetchall()
cursor.close()
I am trying to get the ID of a newly inserted row by using OUTPUT. However, I encountered the HY010 error. The following query/code is what I use:
string = """
SET NOCOUNT ON;
DECLARE #NEWID TABLE(ID INT);
INSERT INTO dbo.t1 (Username, Age)
OUTPUT inserted.id INTO #NEWID(ID)
VALUES(?, ?)
SELECT ID FROM #NEWID
"""
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
the last line id = cursor.fetchone()[0] led to a HY010 error (see below). Any advice would be greatly appreciated!
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
I was able to reproduce your issue, and I was able to avoid it by retrieving the id value immediately after the INSERT and before the commit. That is, instead of
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
I did
cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0] # although cursor.fetchval() would be preferred
cursor.commit()
For me only this worked with Azure SQL Serverless (using pyodbc==4.0.28):
cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT ##IDENTITY AS ID;")
return cursor.fetchone()[0]
If you're using SQLAlchemy with an engine, then you can retrieve the PyODBC cursor like this before running the query and fetching the table ID.
connection = sql_alchemy_engine.raw_connection()
cursor = connection.cursor()
result = cursor.execute(
"""
INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId
VALUES (?, ?);
""",
col1_value,
col2_value,
)
myTableId = cursor.fetchone()[0]
cursor.commit()
print("my ID is:", myTableId)
I think I'm going mad, so please, your help will be appreciated...
I'm experimenting with RDS from AWS and I've setup a simple MySQL database.
One table: MyTable: id (int, auto increment), col1 (varchar(64)), col2 (int).
I try the following code, but fail to get things working properly:
myString = base64.standard_b64encode("myTestString")
myInt = 0
config = {
'user': db_username,
'password': db_password,
'host': db_host,
'database': db_database,
'raise_on_warnings': True,
'charset' :'utf8',
}
cnx = mysql.connector.connect(**config)
cursor1 = cnx.cursor()
SQLa = ("INSERT INTO myTable (col1, col2) VALUES (%s, %s)")
SQLav = (myString, myInt)
cursor1.execute(SQLa, SQLav)
cnx.commit()
cursor2 = cnx.cursor()
SQLq = ("SELECT id, col1, col2 FROM myTable WHERE col1 = '%s'")
SQLv = (myString)
cursor2.execute(SQLq, SQLv)
print cursor2.rowcount
rows = cursor2.fetchall()
for row in rows:
print(row)
cursor1.close()
cursor2.close()
cnx.close()
The INSERT works, within the MySQL Workbench I see the row added.
The SELECT though always returns -1!
I've tried without the '' in the SELECT, but I get an error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '%s' at line 1
How can I make this work?
Thank you!
Your query takes %s and wraps it in '', which means the mysql connector sees this as a string literal, not as a placeholder to be replaced by your values.
Remove the '' around %s and it should work fine.
SQLq = ("SELECT id, col1, col2 FROM myTable WHERE col1 = '%s'")
becomes
SQLq = ("SELECT id, col1, col2 FROM myTable WHERE col1 = %s")
Also, the SQLv = (mystring) does not become a tuple, it is still a string
To make SQLv a tuple, you have to add a comma (not very intuitive)
SQLv = (mystring, )
I'm using Connector/Python to update a MySQL database from a Python script.
update_table = ("UPDATE Users "
"SET `%s` = %s "
"WHERE Id = %s ")
cursor.execute(update_table, (columnname, value, id))
And I get this error:
ProgrammingError: 1054 (42S22): Unknown column ''ColumnName'' in 'field list'
while I do have a column called ColumnName. I think there's some problem with the quotes, i.e. it might be looking for 'ColumnName' instead of ColumnName, but, for example, if I remove the backticks (`) and the update_table looks like this:
update_table = ("UPDATE Users "
"SET %s = %s "
"WHERE Id = %s ")
cursor.execute(update_table, (columnname, value, id))
I get this other error:
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ColumnName' = 'Somebody' WHERE Id = '0000'' at line 1
Any idea about how to fix this?
Thanks in advance.
To the ones wondering about how I solved this problem:
update_table = ("""UPDATE Users
SET %s = '%s'
WHERE Id = '%s' """)
cursor.execute(update_table%(columnname, value, id))
Thanks to furas and John Ruddell for the tips.
So I am trying to get a simple program to insert information into a sqlite db.
The line that is breaking is the cur.execute
sitename = "TEST sitename2"
siteusername = "TEST siteusername2"
sitepasswd = "TEST sitepassword2"
cur.execute("INSERT INTO mytable(sitename, siteusername, sitepasswd) VALUES(%s, %s, %s)", (sitename, siteusername, sitepasswd))
Error that I receive from Python:
sqlite3.OperationalError: near "%": syntax error
You simply have the wrong parameter style.
>>> import sqlite3
>>> sqlite3.paramstyle
'qmark'
Change your code to:
cur.execute("""INSERT INTO mytable(sitename, siteusername, sitepasswd)
VALUES (?, ?, ?)""", (sitename, siteusername, sitepasswd))