While the code is significantly more readable, a new problem arises: spelling. However, to me, this is still very error prone. In other words, as long as we spell our column names correctly, we can use any casing to retrieve that exact cell of data. Even better, we can treat the Row as a case insensitive dictionary. The Row object is quite nice as it lets us continue using regular indices as not to break existing code. Instead of storing each row as a tuple, this row factory stores all rows as a Row object. Well, one option is to use one of the provided row factories for sqlite3, Row. Of course, pretty much everyone says not to use this feature since it’s inefficient, so what do we do? With the row factory, we can dictate exactly how we want the rows to be returned. Now, fortunately, the developers of sqlite3 were aware of this problem, so they exposed a row factory. In no time, our code is going to be packed full of magic numbers. As a result, we have to go back to our table structure and query to figure out exactly what information is at each index. Personally, I didn’t quite care for this because there’s no information in a tuple to tell me what value is at each index. Users: list = cur.execute("SELECT * FROM users").fetchall() Any ideas how that data is formatted? Just a list of tuples. Sure, we can write a normal SELECT query, but how exactly does that data come back? In sqlite3, we have to run our query and fetch the result from our cursor object. Of course, things get a little tricky when we want to get data from the database. cur = connection.cursor()Ĭur.execute("INSERT INTO users (name) VALUES (?)", ("Jeremy",)) That’s easy enough! We make a cursor object and write out our query. Chances are we want to make a series of queries to add, update, and get data. Now let’s imagine we have an established database with data already in it. We provide the path to a SQLite file, and the library lets us execute SQL commands as strings on that database. Basically, it’s a really thin SQLite wrapper. 2 Converting Rows to Custom Objects Making Sense of sqlite3įirst things first, let’s talk about how sqlite3 works.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |