Sqlite3 help
Sibylle Koczian
nulla.epistola at web.de
Sat Oct 18 06:27:37 EDT 2014
Am 14.10.2014 15:36, schrieb Chuck:
> I am building a simple podcast program where I download all the data from a feed with feedparser and store the data in sqlite3. I am spanking new to sqlite and database programming. Should I create the database in the __init__ method of my class, or is that a bad idea. I haven't done any designing that included databases.
>
> Thanks!
> Chuck
>
When I first answered this question, I sent the answer erroneously to
the OP and not to the list. So here it is again.
On Tue, Oct 14, 2014 at 1:19 PM, Sibylle Koczian wrote:
>
> As I don't know anything at all about podcasts and feeds, I'll just
> answer your question about creating the database in the __init__
> method of your class:
>
> That would destroy the existing database and create a new one without
> any data. If you don't want to keep data from former runs of your
> application, this wouldn't be necessary, because you could just
> delete the data and keep the database. But most probably you want to
> keep your data and add to it. In this case, you certainly don't want
> to create a new database.
>
> The __init__ method of your class might be the right place to open
> the database, though.
>
> You know that the documentation for the sqlite3 module is part of the
> Python documentation? It contains links to the SQLite web page and to
> a website with beginner information about SQL itself. So that should
> help to get you started.
Am 15.10.2014 18:51, schrieb Chuck Johnson:
>
> I was thinking that I could fix that by using ' ' ' CREATE TABLE IF
> NOT EXISTS ' ' ' Should I make the sqlite3.connect() command a
> global variable? I am not sure about how to design this properly.
>
That should work. I wouldn't make the connection a global variable. Use
it as a parameter for every function that needs it. Roughly like this:
import sqlite3
# other imports as needed
def one_of_my_functions(myconn, my_other_parameters):
mycurs = myconn.cursor()
try:
# do things with mycurs and my_other_parameters
finally:
mycurs.close()
myconn.commit()
# more of the same ...
def main():
conn = sqlite3.connect('path/to/my/database')
try:
one_of_my_functions(conn, params)
# more of the same
finally:
conn.close()
if __name__ == "__main__":
main()
Or, if your program gets bigger, you might start and stop a connection
inside a function instead of keeping one connection open for all of the
application.
HTH
Sibylle
More information about the Python-list
mailing list