Chen Tabachnik
Chen Tabachnik

Reputation: 33

trying to insert a value to the mySQL data base

mycursor = mydb.cursor()


sql = "INSERT INTO questions q VALUES %s"
val = ("why"),
mycursor.execute(sql, val)

mydb.commit()

getting this 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 'q VALUES 'why'' at line 1

anyone know why?

Upvotes: 1

Views: 118

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65313

Looks like your corresponding column name is followed by the table name is q and %s should be wrapped with parentheses, and remove the comma after ("why") ( I assume column q is of string type ) :

import mysql.connector
from mysql.connector import Error

def insQuestions(i_q):
try:

    mydb = mysql.connector.connect(host='localhost',
                                         database='mydbname',
                                         user='myschema',
                                         password='mypwd')

    mycursor = mydb.cursor()    

    sql = "INSERT INTO questions(q) VALUES (%s)" 

    val = (i_q)
    mycursor.execute(sql, val)

    mydb.commit()
    print("One record inserted successfully")

except mysql.connector.Error as error:
    print("Failed to insert into the table {}".format(error))


insQuestions('why')

Upvotes: 1

Fahad Bhuyian
Fahad Bhuyian

Reputation: 325

You can try this also

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
     user="yourusername",
     passwd="yourpassword",
     database="mydatabase"
    )

    mycursor = mydb.cursor()

   sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
   val = ("John", "Highway 21")
   mycursor.execute(sql, val)

   mydb.commit()

Try This

Upvotes: 0

Related Questions