Skip to content Skip to sidebar Skip to footer

Inserting Tuple's Elements To Database

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 t

Solution 1:

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)

Solution 2:

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

Post a Comment for "Inserting Tuple's Elements To Database"