golang - database / sql learning package

1, database / sql package

sql package provides assurance SQL or SQL-like database of generic interface.

Must be injected (at least) a database driven using sql package.

(1) obtain mysql driver: go get -v github.com/go-sql-driver/mysql

(2) Code Example:

main Package 

Import ( 
	"Database / SQL" 
	"FMT" 
	"log" 
	"Time" 

	_ "github.com/go-sql-driver/mysql" 
) 

// check for errors 
FUNC checkErr (ERR error) { 
	IF ERR! = {nil 
		log.Fatalln (ERR) 
	} 
} 

// transaction error 
FUNC checkTxErr (ERR error, TX * sql.Tx) { 
	IF ERR! = nil { 
		log.Println (ERR) 
		ERR = tx.Rollback () 
		checkErr (ERR) 
	} 
} 

// database entity 
type struct {the User 
	ID int 
	the Name String 
	Age int 
	Sex int 
	AddDate time.time 
} 

FUNC main () { 
	//. 1, database connection
	db, ERR: = sql.Open ( "MySQL", "root:? @ 123456 tcp (127.0.0.1:3306) / = the Test parseTime to true") 
	checkErr (ERR) 
	the defer db.Close () 
	fmt.Println ( "Database connection success ") 
	// 2, to determine whether a valid connection 
	ERR = db.Ping () 
	checkErr (ERR) 
	fmt.Println (" valid database connection ") 
	// 3, create a table 
	SQL: =` 
		the cREATE tABLE iF the NOT EXISTS the Users ( 
			the INT the AUTO_INCREMENT the NOT NULL ID, 
			name VARCHAR (100) the NOT NULL, 
			Age the INT the NOT NULL, 
			Sex TINYINT, 
			add_date DATETIME, 
			a PRIMARY KEY (ID) 
		) 
	` 
	_, ERR = db.Exec (SQL) 
	checkErr (ERR) 

	//. 4, add data  
	// sql = "INSERT INTO users ( name, age, sex, add_date) VALUES (?,?,?,?)"
	// res, err: = db.Exec ( sql, " Joe Smith", 18, 1, time.Now())
	// checkErr(err)
	// fmt.Println(res.LastInsertId())

	//5、查询数据
	sql = "SELECT id,name,age,sex,add_date FROM users"
	rows, err := db.Query(sql)
	checkErr(err)
	defer rows.Close()
	user := User{}
	for rows.Next() {
		err = rows.Scan(&user.ID, &user.Name, &user.Age, &user.Sex, &user.AddDate)
		checkErr(err)
		fmt.Println(user, user.AddDate.Format("2006/01/02 15:04:05"))
	}
	err = rows.Err()
	checkErr(err)

	//6、查询一行
	sql = "SELECT id,name,age,sex,add_date FROM users"
	row := db.QueryRow(sql)
	err = row.Scan(&user.ID, &user.Name, &user.Age, &user.Sex, &user.AddDate)
	checkErr(err)
	fmt.Println(user)

	//7、命令
	sql = "UPDATE users SET name=? WHERE id=?;"
	stmt, err := db.Prepare(sql)
	checkErr(err)
	defer stmt.Close()
	result, err := stmt.Exec("李四", 1)
	checkErr(err)
	fmt.Println(result.RowsAffected())

	//8、查询
	sql = "SELECT id,name,age,sex,add_date FROM users WHERE id=?"
	stmt2, err := db.Prepare(sql)
	checkErr(err)
	defer stmt2.Close()
	row = stmt2.QueryRow(1)
	err = row.Scan(&user.ID, &user.Name, &user.Age, &user.Sex, &user.AddDate)
	checkErr(err)
	fmt.Println(user)

	//9、事务
	tx, err := db.Begin()
	checkErr(err)
	_, err = tx.Exec("UPDATE users SET age=? WHERE id=?", 20, 1)
	checkTxErr(err, tx)
	_, err = tx.Exec("UPDATE users SET sex=? WHERE id=?", 1, 1)
	checkTxErr(err, tx)
	err = tx.Commit()
	checkTxErr(err, tx)

	//10、查询一行
	sql = "SELECT id,name,age,sex,add_date FROM users"
	row = db.QueryRow(sql)
	err = row.Scan(&user.ID, &user.Name, &user.Age, &user.Sex, &user.AddDate)
	checkErr(err)
	fmt.Println(user)

}

2, database

2.1、type DB struct{}

DB is a database handle, representing a connection pool having a plurality of zero to the underlying connection.

It can be safely used simultaneously by multiple go away.

Pool size can be controlled by SetMaxIdleConns method.

2.2, a common method

(1)func Open(driverName, dataSourceName string) (*DB, error)

Open the database, the database returns a handle, DB can be safely used simultaneously by multiple go away, and will maintain its own idle connection pool.

Open function only called once, rarely needs to close DB.

(2)func (db *DB) Driver() driver.Driver

Lower driver returns the database.

(3)func (db *DB) Ping() error

Checks whether the connection to the database is still valid, and if needed to create a connection.

(4)func (db *DB) Close() error

Close the database, the release of any open resources.

DB generally does not close, because DB handles are often shared by multiple go away, and long-term active.

(5)func (db *DB) SetMaxOpenConns(n int)

Sets the maximum number to establish a connection with the database.

If n is greater than 0 and less than the maximum number of idle connections, the maximum number of idle connections will limit the number of connections is reduced to match the maximum opening.

If n <= 0, the maximum does not limit the number of open connections, the default is 0 (unlimited).

(6)func (db *DB) SetMaxIdleConns(n int)

Sets the maximum number of idle connection pool.

If n is greater than the maximum number of open connections, the new maximum number of idle connections are reduced to match the limitations of the maximum number of open connections.

If n <= 0, idle connections are not retained.

(7)func (db *DB) Exec(query string, args ...interface{}) (Result, error)

Execute a command (including the query, delete, update, insert, etc.), execution does not return any results.

Args parameter represents a parameter placeholder in the query.

(8)func (db *DB) Query(query string, args ...interface{}) (*Rows, error)

Perform a query returns multiple rows result (ie Rows), typically used to execute the select command.

(9)func (db *DB) QueryRow(query string, args ...interface{}) *Row

Perform a query, and expected to return at most one row result (ie, Row).

Always return a non-nil value, Scan method until the return value is called, it will return an error delayed.

(10)func (db *DB) Prepare(query string) (*Stmt, error)

Create a ready state for subsequent queries and commands.

The return value can perform multiple queries and commands at the same time.

(11)func (db *DB) Begin() (*Tx, error)

Start a business.

Database isolation level decision driven by.

3, Data Sheet

3.1、type Rows{}

Rows is the result of the query.

It cursor points to the zeroth row of the result set, the Next method results through the rows.

3.2, a common method

(1)func (rs *Rows) Columns() ([]string, error)

Returns the column name.

If Rows has been closed returns an error.

(2)func (rs *Rows) Scan(dest ...interface{}) error

Scan the current line filled into columns results in each of the specified value dest.

If a parameter type is * [] byte, Scan will save a copy of the corresponding data of the copy to the caller, safe, modification, or stored indefinitely.

If the argument is * RawBytes avoided copy; see the documentation for RawBytes constrained its use.

If the type of a parameter of * interface {}, Scan conversion will not copy the values ​​in the bottom drive provided.

If the value of the type [] byte, the data will be copied, the caller can use the security value.

(3)func (rs *Rows) Next() bool

Next ready for the next row in the result Scan method.

If successful, it will return true if there is no next line or an error will return false.

Scan method call every time, even the first call to this method, you must first call the Next method in front.

(4)func (rs *Rows) Close() error

Close Rows, prevent its further list.

If the Next method returns false, Rows will automatically shut down.

Check the results of the method Err conditions.

Close method is idempotent (multiple calls ineffective success) does not affect the result Err methods.

(5)func (rs *Rows) Err() error

Err return possible, errors occur when iteration.

Err to be called after the explicit or implicit call Close method.

4, data lines

4.1、type Row{}

QueryRow method returns a Row, on behalf of single-row query results.

4.2, a common method

(1)func (r *Row) Scan(dest ...interface{}) error

Scan line The query results are stored into the columns specified parameter value dest.

If the query matches multiple lines, Scan will use the first row of the result and discard the remaining lines.

If there are no matching rows query, Scan will return ErrNoRows.

5, SQL command status

5.1、type Stmt struct{}

Stmt is ready state.

Stmt can safely be used simultaneously multiple go away.

5.2, a common method

(1)func (s *Stmt) Exec(args ...interface{}) (Result, error)

Ready to execute commands using parameters provided a good state, return Result type of the state executive summary of the results.

(2)func (s *Stmt) Query(args ...interface{}) (*Rows, error)

Using parameters provided execute the prepared query status, type Rows return query results.

(3)func (s *Stmt) QueryRow(args ...interface{}) *Row

Using parameters provided prepared query execution state.

If you encounter an error in the implementation, the error will be delayed, if released is called Scan method until the return value.

Always return a non-nil.

If the query is not a result, * Scan Row return type of the method will return ErrNoRows; otherwise, Scan method will discard the scanning result and the first row of the remaining rows.

(4)func (s *Stmt) Close() error

Disabled.

6, affairs

6.1、type Tx struct{}

Tx on behalf of a database transaction in progress.

A transaction must end with a call to the Commit or Rollback.

After calling Commit or Rollback, all operations will be on the transaction fails and returns an error value ErrTxDone.

6.2, a common method

(1)func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)

Execute commands, but does not return a result. Such as the implementation of insert and update.

(2)func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)

Execute the query and returns the result of zero to multiple rows (Rows), generally performs the select command.

(3)func (tx *Tx) QueryRow(query string, args ...interface{}) *Row

Execute the query and the results expected to return at most one row (Row).

Always return a non-nil result, query failed errors will be delayed to release in the Scan method calls that result.

(4)func (tx *Tx) Prepare(query string) (*Stmt, error)

Prepare a dedicated to the affairs of state.

Return of the transaction exclusive state after the operation can not be used in the Tx will submit a rollback.

(5)func (tx *Tx) Stmt(stmt *Stmt) *Stmt

Use state that already exist a particular state of the transaction.

(6)func (tx *Tx) Commit() error

Commit the transaction.

(7)func (tx *Tx) Rollback() error

Roll back the transaction.

Guess you like

Origin www.cnblogs.com/dzhy/p/11065300.html