dictionary variable formatting in Python's Mysqldb - python

i'm trying to use dictionary variable in mysqldb insert statement in python 2.7 :
cursor.execute("INSERT INTO DCPOWERSTATS(TS,TOTALPOWER,ITPOWER,AVAILABLEPOWER,PuE) VALUES (%s %s %s %s %s)",(dict_timestamp[key], dict_ABFeeds[key], dict_ABITLOAD[key], 1400, PuE))
and the table is :
sql_createpowertable = '''CREATE TABLE IF NOT EXISTS DCPOWERSTATS (TS DATETIME ,TOTALPOWER FLOAT,ITPOWER FLOAT, AVAILABLEPOWER FLOAT, PuE FLOAT)'''
cursor.execute(sql_createpowertable) .
when i try this I get the error:
_mysql_exceptions.ProgrammingError: (1064, "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 '483.9 334.4 1400 1.44706937799043)' at line 1")

You need commas after each %s in the insert statement:
INSERT INTO DCPOWERSTATS(TS,TOTALPOWER,ITPOWER,AVAILABLEPOWER,PuE) VALUES (%s, %s, %s, %s, %s)

Related

Use table names as sql parameters in python [duplicate]

I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))

How to write proper MySQL Insert statement in Python?

I am trying to insert two columns of data into a MySQL table from Python. And my Insert statement is true, I guess. But I am still getting 1064 error code.
This is for MySQL server version 8.0.12 and Python 3.7. I had tried changing different methods of inserting dynamic variables.
#alter is the data value read from serial port
sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")
I am getting this error message
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 ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1
And I am expecting that these read tag values are inserted successfully​.
Identifiers (e.g. column and table names) in MySQL (and most other flavors of SQL as well) do not take single quotes. They take either no quotes, double quotes, or maybe backticks in the case of MySQL. Try this version:
sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()

mysql.connector.errors.ProgrammingError: Error in SQL Syntax

I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s")
cursor.execute(query, (info, shipDate, warranty, name, sn, ))
conn.commit()
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 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.
No , before the WHERE statement

python sql escape forward slash not working

I am trying to execute an sql statement that should add some data to a database like so:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( db.escape_string(self.imdbID), self.name))
I have also tried:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( self.imdbID, self.name))
But i keep getting this error regardless of using the escape_string or not. See below:
MySQLdb._exceptions.ProgrammingError: (1064, "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 '/name/nm0991810, Mahershala Ali)' at line 1")
I am pretty sure it has to do with the forward slash but i cant get it to work. How do i fix this issue?
If any more information is needed let me know!
Do this instead:
query = "INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)"
cursor.execute(query, (self.imdbID, self.name))
If I am not mistaken mysqldb takes care of this for you.
Otherwise you can do:
cursor.execute(query, (db.escape_string(self.imdbID), self.name))

Python insert into %s MySQL

I am trying to insert some data into a database using the variable test as the table name. But unfortunately I cant seem to achieve this. Can anyone help me out?
From my raise I am getting:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
My code:
test = "hello"
# Open database connection
db = MySQLdb.connect("127.0.0.1","admin","password","table" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()
# disconnect from server
db.close()
I don't think MySQLdb lets you use parameters for table names -- usually this is used for actual parameters (ones that are sometimes from user input and need sanitization - the name/age/gender part gets this right). You could use Python's string formats to achieve this:
sql = ("""INSERT INTO {table} (name, age, gender)
VALUES (%s, %s, %s)""".format(table=table), (test))
Something like this will work:
sql = """INSERT INTO %s (name, age, gender)
VALUES (%s, %s, %s)""" % (test, "%s", "%s", "%s")
You need to separate Python's string substitution from MySQL's parameter substitution. The above is a crude approach, but minimally different from your own code.

Categories