type DB
type DB接口是database/sql包中的核心接口之一,它定义了一系列的方法,用于执行SQL查询、事务管理等操作,如表1所示。
| 方法 | 描述 | 返回值类型 |
|---|---|---|
| (db *DB)Begin() | 开启指定事务。 | *Tx, error |
| (db *DB)BeginTx(ctx context.Context, opts *TxOptions) | 启动指定事务隔离级别的事务,给定的上下文会持续使用到事务提交或回滚为止。若上下文被取消,database/sql包将回滚事务。 | *Tx, error |
| 关闭数据库并释放所有已打开的资源。 | error | |
| (db *DB)Exec(query string, args ...interface{}) | 执行不返回数据行的操作。 | Result, error |
| (db *DB)ExecContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行不返回数据行的操作。 | Result, error |
| (db *DB)Ping() | 检查数据库连接是否仍然有效,并在有需要时建立连接。 | error |
| (db *DB)PingContext(ctx context.Context) | 在给定上下文中检查数据库连接是否仍然有效,并在有需要时建立连接。 | error |
| (db *DB)Prepare(query string) | 为后续的SQL语句创建预处理语句。 | *Stmt, error |
| (db *DB)PrepareContext(ctx context.Context, query string) | 在给定上下文中为后续的SQL语句创建预处理语句。 | *Stmt, error |
| (db *DB)Query(query string, args ...interface{}) | 执行查询并返回多行数据。 | *Rows, error |
| (db *DB)QueryContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行查询并返回多行数据。 | *Rows, error |
| (db *DB)QueryRow(query string, args ...interface{}) | 执行查询并返回单行数据。 | *Row |
| (db *DB)QueryRowContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行查询并返回单行数据。 | *Row |
参数说明
| 参数 | 参数说明 |
| ctx | 表示给定的上下文。 |
| query | 表示待执行的SQL语句。 |
| args | 表示待执行SQL语句需要绑定的参数。支持按位置绑定和按名称绑定,参见如下示例。 |
| opts | 表示事务隔离级别和事务访问模式。事务隔离级别(opts.Isolation)支持sql.LevelReadUncommitted、sql.LevelReadCommitted、sql.LevelRepeatableRead、sql.LevelSerializable。事务访问模式(opts.ReadOnly)支持true(read only)和false(read write)。 |
- Query类方法Query()、QueryContext()、QueryRow()、QueryRowContext()用于执行返回数据行的语句。
- Exec类方法Exec()、ExecContext()用于执行不返回数据行的语句。
- 若使用Query类方法执行DML操作,则可能出现执行结果与预期不符的情况。因此不建议使用Query类方法执行增、删、改操作。
示例
// 前置条件是已经连接数据库,连接对象为db。
// 建表
_, err = db.Exec("CREATE TABLE test_bound(id int, name text)")
// 按位置绑定
_, err = db.Exec("INSERT INTO test_bound(id, name) VALUES(:1, :2)", 1, "张三")
if err != nil {
log.Fatal(err)
}
// 按名称绑定
_, err = db.Exec("INSERT INTO test_bound(id, name) VALUES(:id, :name)", sql.Named("id", 1), sql.Named("name", "张三"))
if err != nil {
log.Fatal(err)
}