Using SQLite in a Python program

后端 未结 8 699
逝去的感伤
逝去的感伤 2020-12-31 06:28

I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don\'t really know how to call it properly. All the

8条回答
  •  迷失自我
    2020-12-31 07:09

    • Sqlite doesn't throw an exception if you create a new database with the same name, it will just connect to it. Since sqlite is a file based database, I suggest you just check for the existence of the file.
    • About your second problem, to check if a table has been already created, just catch the exception. An exception "sqlite3.OperationalError: table TEST already exists" is thrown if the table already exist.
    import sqlite3
    import os
    database_name = "newdb.db"
    if not os.path.isfile(database_name):
        print "the database already exist"
    db_connection = sqlite3.connect(database_name)
    db_cursor = db_connection.cursor()
    try:
        db_cursor.execute('CREATE TABLE TEST (a INTEGER);')
    except sqlite3.OperationalError, msg:
        print msg
    

提交回复
热议问题