如何使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.
- The sqlite C documentation mentions the querystring format but not the existence of the target file.
- The C# connection strings have a
FailIfMissing
option but are in a different format.
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>
- sqlite C文档提到了查询字符串格式,但是没有目标文件的存在。 li>
- C#连接字符串具有
FailIfMissing code>选项,但格式不同。 li> ul>
这与如果缺少数据库,则使SQLite连接失败? (已删除/移动),但用于golang而不是C#。 golang驱动程序似乎使用不同的格式来描述与C#驱动程序的连接,因此我不知道那里的答案是否翻译成golang。 p> div>
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