0

I am trying to make dynamic insert command into mysql, from dictionary values in one transaction but getting an error. Also I was wondering what is the most efficient way to perform this specific case (maybe my code is not optimal)? I am using FOR since in some cases dictionary can be empty. Thanks

    import mysql.connector
    mydb = mysql.connector.connect(..........
    mycursor = mydb.cursor()
    varStatic="test"
    cust={'74.2': '54', '172.26': '76', '7': 'B9'}
    insertStatement='"""INSERT INTO customers (id,number,desc) VALUES (%s,%s,%s)"""'
    for key in cust:
          insertStatement+=',('+key+','+cust[key]+','+varStatic+')'
    mycursor.execute(insertStatement)
    mydb.commit()
8
  • what error do you get? Commented Nov 19, 2018 at 20:43
  • 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 '"""REPLACE INTO customers (id,number,desc) VALUES (%s,%s,%s)""",(74.2,54' at line 1 Commented Nov 19, 2018 at 20:46
  • actually, not quite sure what is wrong but in the same time I do not have feeling that my code is based on best practice.. Commented Nov 19, 2018 at 20:47
  • That does look like a syntax error. Maybe you could add a debug print statement something like print insertStatement and update your question with the output. Your using ''s so the """ ends up in your string. Commented Nov 19, 2018 at 20:49
  • I think that maybe this is because values KEY, VALUE, VARSTATIC are not quoted at all Commented Nov 19, 2018 at 20:54

1 Answer 1

1

You may do something like this, but a little confused about how to optimize for-loop and value. If i can get rid of append or replace to List Comprehensions, then you can use insertStatement += ("(%s,%s,%s),"*len(cust.items()))[:-1]

import mysql.connector
mydb = mysql.connector.connect(user="k",passwd="k",db="k")
mycursor = mydb.cursor()
varStatic="test"
cust={'74.2': "54'", '172.26': '76', '7': 'B9'}
insertStatement= """INSERT INTO customers (id,number,desc) VALUES """
value = []
for k,v in cust.items():
    insertStatement += "(%s,%s,%s),"
    value.append(k)
    value.append(v)
    value.append(varStatic)

print(insertStatement[:-1],value)
try:
    mycursor.execute(insertStatement[:-1],value)
    mydb.commit()
except Exception as e:
    print(e)
    mydb.rollback()
Sign up to request clarification or add additional context in comments.

13 Comments

Hi its not working. This is for example output for two elements in dictionary. Something is not properly defined. This is what I am getting with Print statement. INSERT INTO customers (id,number,desc) VALUES (%s,%s,%s),(%s,%s,%s) ['172.26.74.2111', '54.10.EC.0C.1D.6B', 'test', '172.26.74.112232', '54.10.EC.54.92.FD', 'test']
print(insertStatement[:-1]) returns INSERT INTO customers (id,numbers,desc) VALUES (%s,%s,%s),(%s,%s,%s) this is really not correct
you should read this, and not recommend execute sql straight it will cause injection dev.mysql.com/doc/connector-python/en/… @Dejan
I do not understand quite what you want to say? Are you suggesting to do insert one by one? your print of insert statement returns tis very strange and not correct format. Can you please correct it because answer is definetely not OK? print(insertStatement[:-1]) returns INSERT INTO customers (id,numbers,desc) VALUES (%s,%s,%s),(%s,%s,%s) .
mycursor.execute() will pass ['172.26.74.2111', '54.10.EC.0C.1D.6B', 'test', '172.26.74.112232', '54.10.EC.54.92.FD', 'test '] into INSERT INTO customers (id,numbers,desc) VALUES (%s,%s,%s),(%s,%s,%s) . And you don't care about the data type, the function will automatically convert. Of course you can also execute your own sql, but you need to manually process the data to avoid SQL injection. btw, I will not post code I have never run, especially full code. @Dejande
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.