Search code examples
pythonsqllistsqliteinsert

Python and SQLite: insert into table


Having the following table schema:

tablename(
    name varchar[100], 
    age int, 
    sex char[1]
)

Having a list that has 3 rows each representing a table row:

row1 = [laks,444,M]
row2 = [kam,445,M]
row3 = [kam,445,M]

Or should I use something other than list?

Here is the actual code part:

    for record in self.server:
        print "--->",record
        t=record
        self.cursor.execute("insert into server(server) values (?)",(t[0],));
        self.cursor.execute("insert into server(id) values (?)",(t[1],))
        self.cursor.execute("insert into server(status) values (?)",(t[2],));

Inserting the three fields separately works, but using a single line like these 2 example doesn't work.

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t[0],),(t[1],),(t[2],))
self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t),)

Solution

  • conn = sqlite3.connect('/path/to/your/sqlite_file.db')
    c = conn.cursor()
    for item in my_list:
      c.execute('insert into tablename values (?,?,?)', item)