0

I want to insert data to database table with these python 3 script,

cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
  ("Doni", "Jakarta"),
  ("Ella", "Surabaya"),
  ("Fani", "Bandung"),
  ("Galih", "Depok")
]

for val in values:
  cursor.execute(sql, params=val)

db.commit()

print("{} data ditambahkan".format(cursor.rowcount))

but I got error type "TypeError: execute() takes no keyword arguments". could someone help solve this error?

Marian
  • 14,759
  • 6
  • 32
  • 44
Rakhmi
  • 23
  • 1
  • 9

1 Answers1

0

You can directly pass the query and values with it in the form of list.

cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]

for val in values:
    cursor.execute(sql, list(val))

db.commit()

print("{} data ditambahkan".format(cursor.rowcount))

Or you can use executemany to insert all the values at one time.

cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]

cursor.executemany(sql, values)

db.commit()

print("{} data ditambahkan".for
  • thank you for your comment, i have try your script but still error, the new error is "pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 2 parameters were supplied', 'HY000')",i have try for executemany also but still got an error. – Rakhmi Feb 11 '21 at 01:52
  • You are using pyodbc, this runs for the MySQL. I think you need to change the query as well. Please refer the given link for the reference https://stackoverflow.com/questions/43491381/pyodbc-the-sql-contains-0-parameter-markers-but-1-parameters-were-supplied-hy0 – Ritesh Sengar Feb 11 '21 at 01:59
  • I see, thank you for your advice. Finally the script running well, as you said i have to change the query for SQL. – Rakhmi Feb 11 '21 at 02:58