当前位置:网站首页>database/sql
database/sql
2022-06-24 21:07:00 【AcTarjan】
official database/sql Package introduction
Introduce
- stay Go Access the database in , Need to use sql.DB Type is used to create statements and transactions , Execute queries and get results
- One sql.DB Not a database connection , It is an abstraction of a database
- sql.DB Open or close the connection with the actual database through the driver and manage a connection pool as required
- database/sql The package just provides an interface , There is no implementation , Therefore, you also need to import the third-party database driver
- Third party drives should not normally be used directly , Instead, just quote database/sql Methods and types defined in , This helps avoid making your code dependent on the driver
Connect to database
import (
"database/sql" // Just import the driver you need
_ "github.com/go-sql-driver/mysql" //mysql drive
_ "github.com/lib/pq" //postgres drive
)
func main() {
// Avoid repetition open, take db As a global variable or parameter
db, err := sql.Open("mysql", "user:[email protected](127.0.0.1:3306)/dbdemo")
db, err := sql.Open("postgres", "postgres://bob:[email protected]:5432/mydb?sslmode=verify-full")
db, err = sql.Open("postgres", "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full")
if err != nil {
log.Fatal(err)
}
// Only close at the end db
defer db.Close()
// Test connectivity to the database
err = db.Ping()
if err != nil {
// do something here
}
}
Operating the database
- stay MySQL in , The parameter placeholder is ?; stay PostgreSQL In Chinese, it means $N, among N For from 1 The starting number ;SQLite Accept one of the two ;Oracle Begin with a colon in the placeholder , And named it :param1
Inquire about
General query
var (
id int
name string
)
rows, err := db.Query("SELECT id,name FROM users WHERE id = $1", 1)
if err != nil {
log.Fatal(err)
}
//rows Not closed , The underlying connection is busy , Not available in connection pool , Will cause memory leaks
defer rows.Close()
for rows.Next() {
// Exceptions in processing
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
// Handle exceptions at the end
err = rows.Err()
if err != nil {
log.Fatal(err)
}
Single line query
var name string
// No need to close row
err = db.QueryRow("SELECT name FROM users WHERE id = $1", 1).Scan(&name)
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
Precompile query
- The so-called precompiled sentence is to translate this kind of SQL The value in the statement is replaced by a placeholder , It can be regarded as taking SQL Statement templating
- A compilation 、 Multiple runs , The process of analysis and optimization is omitted ; In addition, precompiled statements can prevent SQL Inject
stmt,err := db.Prepare("SELECT id,name FROM users WHERE id = $1")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
rows, err := stmt.Query(1)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
// ...
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
// Precompiled single row query
stmt, err := db.Prepare("SELECT name FROM users WHERE id = $1")
if err != nil {
log.Fatal(err)
}
var name string
err = stmt.QueryRow(1).Scan(&name)
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
modify
- Use Exec() To complete , It is best to use a precompiled statement to complete INSERT,UPDATE,DELETE Or other statements that do not return rows
stmt, err := db.Prepare("INSERT INTO users(name) VALUES($1)")
if err != nil {
log.Fatal(err)
}
res, err := stmt.Exec("Dolly")
if err != nil {
log.Fatal(err)
}
lastId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
rowCnt, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
log.Printf("ID = %d, affected = %d ", lastId, rowCnt)
边栏推荐
- Leetcode (135) - distribute candy
- Power apps Guide
- VMware virtual machine setting static IP
- An example illustrates restful API
- 网络安全审查办公室对知网启动网络安全审查
- Smooth live broadcast | analysis of key technologies for live broadcast pain points
- VIM usage
- 在Dialog中使用透明的【X】叉叉按钮图片
- JMeter parameterization
- 伯克利、MIT、劍橋、DeepMind等業內大佬線上講座:邁向安全可靠可控的AI
猜你喜欢

Appium introduction and environment installation

Pytest testing framework

After screwing the screws in the factory for two years, I earned more than 10000 yuan a month by "testing" and counterattacked

Limit summary (under update)

Interpreter mode -- formulas for dating

The four stages of cloud computing development have finally been clarified

图的基本概念以及相关定义

二叉树的基本性质与遍历

传统的IO存在什么问题?为什么引入零拷贝的?
浅谈MySql update会锁定哪些范围的数据
随机推荐
DAPP system customization of full chain hash game (scheme design)
Berkeley, MIT, Cambridge, deepmind and other industry leaders' online lectures: towards safe, reliable and controllable AI
Web automation: web control interaction / multi window processing / Web page frame
How to apply agile development ideas to other work
Bridging mode -- law firm
Image panr
Wechat applet custom tabbar
Variable setting in postman
Packaging_ Conversion between basic type and string type
Haitai Advanced Technology | application of privacy computing technology in medical data protection
A/b test helps the growth of game business
VIM usage
C语言实现扫雷(简易版)
二叉树的基本性质与遍历
Create a multithreaded thread class
Record a deletion bash_ Profile file
Basic properties and ergodicity of binary tree
等保备案是等保测评吗?两者是什么关系?
What does virtualization mean? What technologies are included? What is the difference with private cloud?
Builder mode -- Master asked me to refine pills