如何使sqlite出错而不是在golang中创建丢失的数据库文件?

如何使sqlite出错而不是在golang中创建丢失的数据库文件?

问题描述:

I'm opening a connection to a sqlite database of the user's choosing in my golang program. If they supply a path to a non-existent file then I want to throw an error instead of creating the file.

I'm using the mattn/gp-sqlite3 driver. The documentation doesn't mention this capability as far as I can see.

This is the same as Make SQLite connection fail if database is missing? (deleted/moved) but for golang instead of C#. The golang driver seems to use a different format for describing connections to the C# driver so I don't know if the answers there translate to golang or not.

我正在golang程序中打开与用户选择的sqlite数据库的连接。 如果它们提供了不存在文件的路径,那么我想抛出一个错误而不是创建文件。 p>

我正在使用 mattn / gp-sqlite3 驱动程序。 据我所知,文档中没有提及此功能。 p>

This is not currently possible with the go-sqlite3 library. Looking at the source, you can see SQLITE_OPEN_CREATE is always passed to the open function:

rv := C._sqlite3_open_v2(name, &db,
    C.SQLITE_OPEN_FULLMUTEX|
        C.SQLITE_OPEN_READWRITE|
        C.SQLITE_OPEN_CREATE,
    nil)

I would suggest you open a ticket on the package to add such functionality.

In the mean time, you could add the following code before your DB is created (keep in mind that a race condition exists, which is why you should still request this feature in the library itself):

_, err := os.Stat("db.sqlite3")
if os.IsNotExist(err) {
    panic("database doesn't exist")
}
// TODO: create db