Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't insert single column value in python using MySQL

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()
like image 897
user6875880 Avatar asked Dec 23 '16 23:12

user6875880


People also ask

How can I add values to a specific column in mysql?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

How do you add a column to a database in Python?

The syntax for adding a column with ALTER statement: ALTER TABLE table_name ADD new_column_name column_definition [FIRST | AFTER column_name];


1 Answers

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,))
like image 69
thebjorn Avatar answered Sep 20 '22 00:09

thebjorn