views:

851

answers:

2

I have a list that has 3 rows each representing a table row:

>>> print list
[laks,444,M]
[kam,445,M]
[kam,445,M]

How to insert this list into a table?

My table structure is:

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

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

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

or

self.cursor.execute("insert into server(server,c_id,status) values (?,?,?)",(t),)

does not.

+2  A: 

Adapted from http://docs.python.org/library/sqlite3.html:

# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)
Dyno Fu
+2  A: 
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)
Dominic Rodger
Thanks Dyno and Dominic - But it's not working - this is what i'm trying ----------- for record in list: print "--->",record cursor.execute("insert into process values (?,?,?)",record);-----------getting error
lakshmipathi
@lakshmipathi - What error do you get?
Dominic Rodger
I have try, except part - try part will have for loop and execute stmt and except part has single message saying "insert failed" ...it just prints the message from except part and quits.How to debug this more effectively ?
lakshmipathi
@lakshmipathi: If your exception handling is chewing up the error message then it isn't really handling it...
Ignacio Vazquez-Abrams
how to print error number .. atleast that would provide some hint
lakshmipathi