Python Sqlite agregando una fila

I have a local sqlite server. The SQL database only contains a table called flights. This table flights only contains two columns: dt y flight. It is created like so: CREATE TABLE IF NOT EXISTS flight (dt INT NOT NULL, flight INT PRIMARY KEY);. dt is meant to stand for datetime. This column dt holds time and date stamps for each flight. The flight column is meant to be an auto increment id for each flight.

I now need to create the flight and record the ID. But I think my method below is incredibly stupid. There has to be a better way than this. The code below does not work thus adding to the stupidity of my attempt. It returns currently prints (None,).

For added clarification, all I need to do is add a flight with the provided time stamp. Then find the id of the flight I just created. Should be simple enough.

t = (int(time.time()),)
conn, c = AT.startSQLdb()
c.execute("INSERT INTO flight VALUES (?,NULL);",t)
c.execute("SELECT flight FROM flight WHERE dt=?;",t)
print c.fetchone()

Por cierto, AT.startSQLdb() is just a method that returns a tuple (sql connection, sql cursor). I just have it as a function to keep the start up functionality the same for all threads.

preguntado el 04 de julio de 12 a las 03:07

1 Respuestas

You can select the last auto-assigned id with this SQL:

SELECT last_insert_rowid()

BTW: you mention threads, SQLite is not great with concurrent access, so be careful with multiple threads.

Respondido 04 Jul 12, 03:07

For the same effect, from python you can call to: c.lastrowid - Robert

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.