英文:
golang database Open function ambiguity
问题
在Go语言中,你可以使用以下代码来打开一个数据库:
DB, err = sql.Open("sqlite3", "./bar.db")
这将返回一个类型为*sql.DB
的数据库对象,这个函数和类型都是database/sql
包的成员。
然而,在sqlite3驱动包中,还有另一个Open
函数,它返回一个类型为*sqlite3.Conn
的对象。
我注意到,在sqlite3
驱动包中定义的一些函数在使用默认的database/sql
打开的数据库上不起作用。
此外,sqlite3
包中还有一些类似于database/sql
的函数,比如Query
和Exec
,它们返回不同的类型。
database/sql
包中有一个名为Query
的函数,返回类型为*sql.Rows
。
mxk/sqlite/sqlite3
和mattn/go-sqlite3
都有一个Query
函数,但返回的类型完全不同。
我想在我的数据库连接上运行mxk/sqlite/sqlite3
的BusyTimeout
等函数,但它们不是正确的类型。我是否需要重新编写所有代码,使用sqlite3驱动来打开数据库连接,而不是使用database/sql
的Open
函数?如果不能使用任何驱动程序的函数,database/sql
的Open
函数有什么优势呢?
英文:
In go, you invoke a database open with
DB, err = sql.Open("sqlite3", "./bar.db")
This returns a database of type *sql.DB
, the function and type are both members of database/sql
.
However, in the sqlite3 driver package, there is another Open
function which returns a *sqlite3.Conn
type.
I've noticed that some of the functions defined in the sqlite3
driver package do not work on a database opened using the default database/sql
.
Additionally, there are functions in the sqlite3 package that are similar to database/sql
's functions, namely Query
and Exec
, which return different types.
database/sql
contains a func Query
that returns type *sql.Rows
.
mxk/sqlite/sqlite3
and mattn/go-sqlite3
both have a Query
function, which return completely different types.
I want to run functions such as mxk/sqlite/sqlite3
's BusyTimeout
on my database connection, but it isn't the correct type. Do I have to re-write all of my code to open the database connection with the sqlite3 driver instead of using database/sql
's Open
? What's the advantage of database/sql
's Open
function if you can't use any of the driver's functions with that generic connection?
答案1
得分: 2
好的,以下是翻译好的内容:
根据文档所述...
> 数据库连接可以通过直接使用此包或使用“sqlite3”数据库/SQL驱动程序来创建。直接接口在下面进行了描述,它公开了SQLite特定的功能,例如增量I/O和在线备份。当您的应用程序需要支持多个数据库引擎时,建议使用驱动程序。
... 当您需要使用SQLite特定功能(您的用例)时,您将使用sqlite3连接,而对于通用数据库连接,您将使用数据库驱动程序(您的代码)。
这是非常合乎逻辑的,因为通用驱动程序如何处理特定于各种数据库的功能呢?运行时错误吗?
所以您有两个选择:所有SQLite功能 -> sqlite连接,或处理多个SQL数据库 -> 通用驱动程序。
英文:
Well, as the docs state...
> Database connections are created either by using this package directly or with the "sqlite3" database/sql driver. The direct interface, which is described below, exposes SQLite-specific features, such as incremental I/O and online backups. The driver is recommended when your application has to support multiple database engines.
... you would use the sqlite3 connection when you want the sqlite specific functions (your usecase) and for generic database connections you would use the database driver (your code).
That is perfectly logical, since how would a generic driver handle functions that are specific to various databases? Runtime errors?
So you have a choice: all sqlite functions -> sqlite conn or handle multiple sql databases -> generic driver.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论