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()
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.
The syntax for adding a column with ALTER statement: ALTER TABLE table_name ADD new_column_name column_definition [FIRST | AFTER column_name];
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,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With