Can't insert single column value in python using MySQL

梦想的初衷 提交于 2021-01-02 08:22:46

问题


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()

回答1:


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,))



回答2:


You can try either of these:

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



回答3:


try this:

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


来源:https://stackoverflow.com/questions/41309096/cant-insert-single-column-value-in-python-using-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!