2013-04-29 184 views

回答

9

是的,SQLAlchemy的不創建一個數據庫使用此代碼

from sqlalchemy import create_engine, ForeignKey 
from sqlalchemy import Column, Date, Integer, String 
from sqlalchemy.ext.declarative import declarative_base 

engine = create_engine('sqlite:///C:\\sqlitedbs\\school.db', echo=True) 
Base = declarative_base() 


class School(Base): 

    __tablename__ = "woot" 

    id = Column(Integer, primary_key=True) 
    name = Column(String) 


    def __init__(self, name): 

     self.name = name  


Base.metadata.create_all(engine) 
+1

因此,如果sqlite數據庫是您指向的那個目錄中的現有文件,它會調用它呢?即:如果存在,連接到它,否則,創建它。我有權這麼說嗎? – 2016-03-29 15:17:48

+0

當然,我發現是這樣。 – Gandalf 2016-05-04 18:16:35

3

我發現(使用SQLite + pysqlite),如果該目錄存在,它會創建它你。我證實,它在Windows上,但如果不存在的目錄中拋出一個異常:

OperationalError: (sqlite3.OperationalError) unable to open database file 

我的解決方法是要做到這一點,但感覺討厭:

if connection_string.startswith('sqlite'): 
     db_file = re.sub("sqlite.*:///", "", connection_string) 
     os.makedirs(os.path.dirname(db_file), exist_ok=True) 
    self.engine = sqlalchemy.create_engine(connection_string) 
+0

對,在這種情況下,我可能只是打印一條消息給用戶說:「對不起,我無法創建數據庫FOO,因爲目錄BAR不存在。」然後,如果用戶想要創建並繼續,他們可以。 – 2016-07-02 18:46:48

+0

對於一個交互式應用程序來說很好,但我也希望它能夠在持續集成環境中工作 – danio 2016-09-23 09:23:21

+1

一旦目錄存在,它就可以持續集成。您必須決定缺失的目錄是否爲錯誤,並且需要用戶干預(在這種情況下,您會生成一條錯誤消息並放棄),或者缺少的目錄是否只是警告或次要異常(在這種情況下,您創建的可能是整個鏈的)目錄並繼續,正如你所說,這是'討厭的'。或者你讓它可配置... – 2016-09-26 18:18:36

相關問題