2009-10-04 4 views
7

데이터베이스 파일이 이미 있는지 확인하려면 어떻게합니까? 그리고 존재하는 경우 이미 특정 테이블이 있는지 여부를 어떻게 확인합니까?sqlite3 in Python

+0

참조 http://stackoverflow.com/questions/211501/using-sqlite-in-a-python-program, http://stackoverflow.com/questions/1449495/can-i- test-for-the-a-table-in-a-sqlite-database –

답변

10

데이터베이스가 있는지 보려면 데이터베이스가 포함되어 있다고 생각하는 파일에 sqlite3.connect을 넣고 쿼리를 실행 해보십시오. 이 하지 데이터베이스의 경우,이 오류가 발생합니다 :

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

sqlite3.connect가 존재하지 않는 경우 데이터베이스를 생성합니다; @johnp가 주석에서 지적한대로 os.path.exists은 파일이 있는지 여부를 알려줍니다.

기존 테이블을 확인하려면 query against sqlite_master. 예를 들면 :

>>> 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 
+1

음 ... sqlite3.connect()를 호출하면 자동으로 데이터베이스가 생성됩니까? – john2x

+0

@ john2x - 예, 있습니다. –

+0

당신은 파일이 사용 os.path.exists() 존재하는지 확인하려면 : ( 수입을 os.path os.path.exists ('dbname.db') 당신이 sqlite3.connect 전에 이 검사를 수행을) 데이터베이스가없는 경우 데이터베이스를 작성하지 마십시오. –