7

I have a single column table. I need to insert values in this column. The program runs correctly without errors. But when I check the database, nothing gets inserted. When I added another column to the code and table, the program inserts data correctly. Can you tell me how to insert data for a single column table? This is the single column code that does not insert anything to the table.

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="123",
                  db="dbname")
cursor = conn.cursor()
x=100
try:
    sql="""INSERT INTO table (col1) VALUES ('%s')"""
    cursor.execute(sql, (x))
    conn.commit()
except:
    conn.rollback()

conn.close()

This is the two columns code.

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="123",
                  db="dbname")
cursor = conn.cursor()
x=100
y=2
try:
    sql="""INSERT INTO table (col1,col2) VALUES ('%s','%s')"""
    cursor.execute(sql, (x,y))
    conn.commit()
except:
    conn.rollback()

conn.close()

3 Answers 3

12

You need to lose the quotes around %s, after that you need to know that the second argument to cursor.execute() is a tuple, and that a one-tuple is written:

(item,)

note the comma. The solution is then:

sql="""INSERT INTO table (col1) VALUES (%s)"""
cursor.execute(sql, (x,))
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this sql="""INSERT INTO table (col1,col2) VALUES (%s)""" cursor.execute(sql, (x,)). It runs but it does not insert the data to DB.
Your two column version is correct if you remove the quotes around the place holders.
0

You can try either of these:

  1. Don't use '%s', you can use ? instead
  2. Instead of '%s', just use %s without quotes

Comments

-3

try this:

sql="""INSERT INTO table (col1) VALUES ({});""".format(x)
cursor.execute(sql)

3 Comments

Please don't forget to explain / comment your code, and provide relevant documentation [from review]
Please avoid code-only answers. Try to explain how your code solves OP's problem. Others that find this question may not be as experienced as you; help them to understand your solution.
This strategy is also a sql-injection waiting to happen (although in this particular case you'll probably get a sql syntax-error first).

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.