英文:
How do I get sqlite to error instead of creating a missing database file in golang?
问题
我正在为您翻译以下内容:
我正在我的 Golang 程序中打开一个用户选择的 SQLite 数据库连接。如果他们提供了一个不存在的文件路径,我希望抛出一个错误而不是创建该文件。
我正在使用 mattn/gp-sqlite3 驱动程序。据我所见,文档中没有提到这个功能。
- SQLite C 文档 提到了查询字符串的格式,但没有提到目标文件的存在与否。
- C# 连接字符串 有一个
FailIfMissing
选项,但格式不同。
这与 https://stackoverflow.com/q/807208/10245 相同,只是针对 Golang 而不是 C#。Golang 驱动程序似乎使用了一种不同的格式来描述与 C# 驱动程序的连接,所以我不知道那里的答案是否适用于 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 https://stackoverflow.com/q/807208/10245 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.
答案1
得分: 8
这在go-sqlite3库中目前是不可能的。从源代码中可以看到,SQLITE_OPEN_CREATE
总是传递给open函数:
rv := C._sqlite3_open_v2(name, &db,
C.SQLITE_OPEN_FULLMUTEX|
C.SQLITE_OPEN_READWRITE|
C.SQLITE_OPEN_CREATE,
nil)
我建议你在该包上提交一个问题,以添加这样的功能。
与此同时,你可以在创建数据库之前添加以下代码(请记住存在竞争条件,这就是为什么你仍然应该在库本身中请求此功能):
_, err := os.Stat("db.sqlite3")
if os.IsNotExist(err) {
panic("database doesn't exist")
}
// TODO: create db
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论