sqlite3 in Python

前端 未结 1 1739
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 06:10

How do I check if the database file already exists or not? And, if the it exists, how do I check if it already has a specific table or not?

1条回答
  •  情话喂你
    2021-01-05 06:37

    To see if a database exists, you can sqlite3.connect to the file that you think contains the database, and try running a query on it. If it is not a database, you will get this error:

    >>> c.execute("SELECT * FROM tbl")
    Traceback (most recent call last):
      File "", line 1, in 
    sqlite3.DatabaseError: file is encrypted or is not a database
    

    sqlite3.connect will create the database if it doesn't exist; as @johnp points out in the comments, os.path.exists will tell you whether the file exists.

    To check for existing tables, you query against sqlite_master. For example:

    >>> def foo(name):
    ...     for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
    ...             if row == (name,):
    ...                     return True
    ...     return False
    ... 
    >>> foo("tz_data")
    True
    >>> foo("asdf")
    False
    

    0 讨论(0)
提交回复
热议问题