当前位置:网站首页>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)
边栏推荐
- 伯克利、MIT、剑桥、DeepMind等业内大佬线上讲座:迈向安全可靠可控的AI
- 图像PANR
- Implement the redis simple client customized based on socket
- How to enhance influence
- 2021-09-30
- Memo mode - game archiving
- The difference between RPC and restful
- Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!
- I just purchased a MySQL database and prompted that there are already instances. The console login instance needs to provide a database account. How do I know the database account.
- 大一女生废话编程爆火!懂不懂编程的看完都拴Q了
猜你喜欢

Postman assertion

Adding subscribers to a list using mailchimp's API V3

Berkeley, MIT, Cambridge, deepmind and other industry leaders' online lectures: towards safe, reliable and controllable AI

Pytest testing framework

Web automation: summary of special scenario processing methods

顺序表的基本操作

Haitai Advanced Technology | application of privacy computing technology in medical data protection

VMware virtual machine setting static IP

Basic properties and ergodicity of binary tree

The four stages of cloud computing development have finally been clarified
随机推荐
Rip/ospf protocol notes sorting
Common data model (updating)
Reflection - class object function - get method (case)
Enjoy yuan mode -- a large number of flying dragons
The Google File System (GFS) learning notes
Docker deploy mysql5.7
红象云腾完成与龙蜥操作系统兼容适配,产品运行稳定
Format method and parse method of dateformat class
Open function
After idea installs these plug-ins, the code can be written to heaven. My little sister also has to arrange it
Mapstacks: data normalization and layered color layer loading
Tool composition in JMeter
Summary of idea practical skills: how to rename a project or module to completely solve all the problems you encounter that do not work. It is suggested that the five-star collection be your daughter
List set Introduction & common methods
Postman assertion
Read all text from stdin to a string
Shrimp skin test surface treated
JMeter parameterization
Basic properties and ergodicity of binary tree
Open programmable infrastructure (OPI) project, redefining dpu/ipu