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.
Related
I am trying to insert a list into 1 single column in a row .How do I make the list go in a column in the same row with the same ID? I cannot get the syntax right.
social_media is a list like this
['https://twitter.com/eddylazzarin?ref=cypherhunter', 'https://www.linkedin.com/in/eddy-lazzarin-66059749?ref=cypherhunter', 'https://a16z.com/author/eddy-lazzarin/?ref=cypherhunter']
This is my code
sql = cursor.execute(f"SELECT inv_id FROM Investors WHERE name =\'{name}\'")
pid = cursor.fetchone()
pidf = str(pid)[1:2]
pidff = int(pidf)
try:
cursor.execute("INSERT INTO team_members(inv_id,mem_name,picture,experience) VALUES(%s, %s, %s, %s)", (pidff, port_name, headshot, work_ex,))
list_str = '|'.join(str(item) for item in so_links)
cursor.execute(f"UPDATE team_members WHERE mem_name=\'{port_name}\' SET social_media ('{list_str}')")
raise e
inv_id is the FOREIGN_KEY.
However I cannot get the right syntax
Error:
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 'WHERE mem_name='Eddy Lazzarin' SET social_media
('https://twitter.com/eddylazzar' at line 1
You have missing = in SET & wrong position of it
cursor.execute("UPDATE team_members SET social_media = %s WHERE mem_name=%s",(list_str,port_name))
see the docs
I keep getting the error information after running this line of code
query = ("INSERT INTO Movies" "(movie_id,movie_name,movie_year,duration,score,storyline,genre,poster)"
"VALUES (%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)s)") #args = (ID,name,year,runtime,rating,storyline,genre,links)
cursor.execute(query)
con.commit()
The format is from mysql document
the error message is
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 '%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)' at line 1
You are missing the query parameters:
cursor.execute(query, args)
where args, since you are using named parameters, has to be a dictionary where the keys should correspond to the parameter names:
args = {
"name": "some name",
"year": 1962,
# ...
}
As a side note, you can put your query into a multi-line string for readability:
query = """
INSERT INTO
Movies
(movie_id, movie_name, movie_year, duration, score, storyline, genre, poster)
VALUES
(%(ID)s, %(name)s, %(year)s, %(runtime)s, %(rating)s, %(storyline)s, %(genre)s, %(links)s)
"""
I met problems while using sqlite3 in python.
def getEntryId(self, table, field, value, createNew=True):
cur=self.con.execute("select rowid from %s where %s = '%s'" % (table, field, value))
res=cur.fetchone()
if res==None:
cur=self.con.execute("insert into %s (%s) values('%s') " % (table, field, value))
return cur.lastrowid
else:
return res[0]
However, I met this:
OperationalError: unrecognized token: "'''". It seems that my 2nd line of codes is incorrect.
I can not figure out why, so I do the same thing:
cu.execute("select rowid from urllist where %s = '%s'" % ('url', 'yes'))
It came out without an error. Why? How could I fix it?
You should parameterize the query. You cannot though parameterize the table and field names, you can use string formatting to insert the table and field names into the query, but make sure you either trust the source, or validate the values properly:
query = "select rowid from {table} where {field} = %s".format(table=table, field=field)
cur = self.con.execute(query, (value, ))
res = cur.fetchone()
The parameterization not only helps to prevent SQL injection attacks, but also handles the data types conversions, escapes the parameters properly, which may fix your current problem as well.
I want to update fields in a table 'my_table', but it reports:
ProgrammingError: (1064, 'You have an error in your SQL syntax; ...
PS: values is a list of strings and len(values) == len(fields)
Expression of sql is:
'update my_table set field_a=\\'%s\\',field_b=\\'%s\\',field_c=\\'%s\\',field_d=\\'%s\\''
Because len(fields) may change when running the program, I use the following codes:
field_str = ''
for field in fields:
field_str += (field + "='%s',")
field_str = field_str[: -1]
sql = "update %s set %s" % (my_table, field_str)
values = [current_response_dict[site][info_type] for site in site_list for info_type in self.all_info_type]
cursor.execute(sql, values)
conn.commit()
The ' are unnecessary. And you have a update without where-clause?
sql = "update %s set %s" % (my_table, ','.join('%s=%%s' % f for f in fields))
values = [current_response_dict[site][info_type] for site in site_list for info_type in self.all_info_type]
cursor.execute(sql, values)
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