Inserting tuple's elements to database

你离开我真会死。 提交于 2019-12-11 17:59:39

问题


I have a tuple that i wanna store its elements, I'm trying to insert it as following and it gives the following error, what am i doing wrong ? records_to_be_inserted is the tuple that has 8 elements.

with self.connection:
        cur = self.connection.cursor()
        cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
                        photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserTed)

Traceback (most recent call last): File "/home/tayfun/workspace/personal_guide/modules/mainwindow.py", line 57, in save_records photo, address, note, date) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", self.records_to_be_inserTed) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 8, and there are 0 supplied.


回答1:


The query must have all the data ready to be inserted. You are calling a function in the query, which i guess you want that provides the data but that wont work. You need to pass all the data in variables or locate them in the tuple index (like: tuple_name[1], tuple_name[4], etc.)

Example:

myTuple = ['a','b','c','d','e','f','g']
cur.executemany("INSERT INTO rehberim(names, phone, mobile, email, \
                    photo, address, note, date) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6}" .format (myTuple[1], myTuple[2], myTuple[3], myTuple[4], myTuple[5], myTuple[6], myTuple[7])



回答2:


Note that the executemany is for inserting multiple rows, e.g.,

import sqlite3

""" the table structure is:
create table tab
    a char(1),
    b char(2),
    c char(3)
)
"""

conn = sqlite3.connect('C:\\test.db')
stmt = "insert into tab (a, b, c) values (?, ?, ?)"

cur = conn.cursor()
## many rows
vals = [('1','2','3'), ('2','3','4'), ('3','4','5')]

cur.executemany(stmt, vals)
cur.close()

This will result in three rows in the database. If it is because you have multiple values in one query, you need to format it!

Edit: Added formatting with dictionaries

By using the following approach you do not need to consider the order of the values in the format call because the key in the dictionary is mapping the value into the {key_word} placeholder.

values = {'a' : 'value_a',
          'b' : 'value_b'}

stmt = "insert into tab (col_a, col_b) values ({a}, {b})".format(**values)


来源:https://stackoverflow.com/questions/8051439/inserting-tuples-elements-to-database

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