sqlalchemy,creating an sqlite database if it doesn't exist

前端 未结 4 987
日久生厌
日久生厌 2021-02-01 04:05

I am trying out sqlalchemy and i am using this connection string to connect to my databases

engine = create_engine(\'sqlite:///C:\\\\sqlitedbs\\\\database.db\')
         


        
4条回答
  •  庸人自扰
    2021-02-01 04:25

    I found (using sqlite+pysqlite) that if the directory exists, it will create it, but if the directory does not exist it throws an exception:

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

    My workaround is to do this, although it feels nasty:

        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)
    

提交回复
热议问题