3

I am trying to insert basic data into my MySQL table without any success yet I'm using basic tutorials as demos.

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

My MySQL

CREATE TABLE awesome (
id int NOT NULL AUTO_INCREMENT,
test varchar(50),
PRIMARY KEY (id)
);

My Python code

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="pass",
database="db"
)

mycursor = mydb.cursor()

sql = "INSERT INTO awesome (test) VALUES (%s)"
val = ("Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")
Blueprov
  • 51
  • 3
  • Add single quotes around `%s` – iScripters Jan 27 '19 at 20:33
  • That would add %s into the database, I need it to add the variable val, Highway 21. – Blueprov Jan 27 '19 at 20:43
  • 1
    Use `val = ("Highway 21",)`. Note the comma; it makes the right-hand side a tuple with one item inside. Without the comma, Python interprets the right-hand side as a string -- it just evaluates the expression inside the parentheses as a string. – unutbu Jan 27 '19 at 21:00
  • @unutbu That solved it, thanks! – Blueprov Jan 27 '19 at 21:09
  • Related: [Python MySQL Connector database query with %s fails](https://stackoverflow.com/q/23600286/190597) – unutbu Jan 27 '19 at 22:10

1 Answers1

2

Yes the problem arises when there is only 1 argument in val tuple. Use

val=("Highway 21",)

Note the comma at the end.

Rahul Soshte
  • 798
  • 8
  • 11