Now that you know how to insert properly, we're going to be covering how to read data from SQLite with the select statement. Re-open the database and table if you like to see how it looks now. This gives us the current time, converted to datestamp, and then a random value for the value column. I need to add the new post with the timestamp being the current time and date and then i need to return the id for this new post. The lastinsertrowid () SQL function is a wrapper around the sqlite3lastinsertrowid () C/C++ interface function. Inserting row into SQLite table Ask Question Asked 8 years, 1 month ago Modified 8 years, 1 month ago Viewed 2k times 0 I'm trying to add a row (post submitted by user) into a SQLite table (posts). Then, we use a one-liner for-loop to run dynamic_data_entry() ten times. All credits to Martijn Pieters in the comments: You can use the function lastinsertrowid (): The lastinsertrowid () function returns the ROWID of the last row insert from the database connection which invoked the function. We comment out the create_table, which we could leave if we wanted, but there is no need for it anymore. Now let's change the end of the script: #create_table() ![]() Note that we are using ? for the variable input. In this function, we set some variables, then we execute a slightly different SQL query. adddata.py import sqlite3 conn nnect('library.db') cursor conn. Next, we'll make a new function, dynamic_data_entry: def dynamic_data_entry():ĭate = str((unix).strftime('%Y-%m-%d %H:%M:%S'))Ĭ.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ?, ?, ?)", We get the first two modules so that we can create the timestamps to use, and then we use random to create some random values to use. In this tutorial, we're going to build on that, covering how to insert dynamically into a database's table, using variables.Ĭode leading up to this point: import sqlite3Ĭ.execute("CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)")Ĭ.execute("INSERT INTO stuffToPlot VALUES(1452549219,' 13:53:39','Python',6)")įirst, let's import a couple new things: import time ![]() In the previous SQLite tutorial, we learned how to create a database, a table, and how to insert data.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |