Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into MySQL table with Python [duplicate]

Tags:

python

mysql

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.")
like image 484
Blueprov Avatar asked Apr 27 '26 23:04

Blueprov


1 Answers

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

val=("Highway 21",)

Note the comma at the end.

like image 71
Rahul Soshte Avatar answered Apr 29 '26 12:04

Rahul Soshte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!