Home  >  Q&A  >  body text

python - I have a question about database insertion

Python3 or sqlite3

info = "'INSERT INTO brush_card_record(brush_card_date, brush_card_time, card_num_6061, card_num_6654) VALUES(?,?,?,?)',('2017-05-28','12:23:32', 123, 0)"

cur.execute(info)

This will report an error: sqlite3.OperationalError

cur.execute('INSERT INTO brush_card_record(brush_card_date, brush_card_time, card_num_6061, card_num_6654) VALUES(?,?,?,?)',('2017-05-28','12:23:32', 123 , 0))

This will work.

某草草某草草2686 days ago821

reply all(4)I'll reply

  • 代言

    代言2017-06-12 09:29:56

    cur.execute has two parameters, one is SQL, and the other is to pass the value to the SQL parameter. Your first sentence enclosed in double quotes is equivalent to a string, that is, a parameter, and the second parameter is not passed in

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-12 09:29:56

    info = "INSERT INTO brush_card_record(brush_card_date, brush_card_time, card_num_6061, card_num_6654) VALUES(%s,%s,%s,%s)"%('2017-05-28','12:23:32', 123, 0)

    或者str.format

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:29:56

    sqlite中是这么定义:
    
    class Connection(object):
        """ SQLite database connection object. """
        def cursor(self, *args, **kwargs): # real signature unknown
            """ Return a cursor for the connection. """
            pass
            
    class Cursor(object):
        """ SQLite database cursor class. """
        def execute(self, *args, **kwargs): # real signature unknown
            """ Executes a SQL statement. """
            pass   
    
    问题中的第一种方式无法自动解包

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:29:56

    The question has been found, thank you for the answer!

    When inserting new data into the database table is dynamic, a better way is to generate str first and then pass it into cur.execute() as a parameter.

    Code example:

    insert_info = '''\
    INSERT INTO %s(brush_card_date, brush_card_time, card_num_6061, card_num_6654) \
    VALUES("%s", "%s", %s, %s)''' % (f_table_name, date, now_time, gold_6061, gold_6654)
    
    cur.execute(insert_info)

    reply
    0
  • Cancelreply