当前位置:网站首页>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)
边栏推荐
- Berkeley, MIT, Cambridge, deepmind et d'autres grandes conférences en ligne: vers une IA sûre, fiable et contrôlable
- An example illustrates restful API
- Docker deploy mysql5.7
- VIM usage
- The difference between RPC and restful
- Memo mode - game archiving
- Comprehensive comparison of the most popular packet capturing tools in the whole network
- Bridging mode -- law firm
- 网络安全审查办公室对知网启动网络安全审查
- List set Introduction & common methods
猜你喜欢

Power apps Guide

How to apply agile development ideas to other work

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

When querying the database with Gorm, reflect: reflect flag. mustBeAssignable using unaddressable value

Responsibility chain mode -- through interview

Nifi fast authentication configuration

二叉树的基本性质与遍历

Summary of message protocol problems

主数据建设的背景

Basic concepts and definitions of Graphs
随机推荐
Geek University cloud native training camp
Responsibility chain mode -- through interview
CVPR 2022 remembers Sun Jian! Tongji and Ali won the best student thesis award, and hekaiming was shortlisted
Appium desktop introduction
Common self realization functions in C language development
Selenium crawl notes
伯克利、MIT、剑桥、DeepMind等业内大佬线上讲座:迈向安全可靠可控的AI
Learn to use a new technology quickly
Prototype mode -- clone monster Army
Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!
二叉树的基本性质与遍历
Haitai Advanced Technology | application of privacy computing technology in medical data protection
Static routing job
Record a deletion bash_ Profile file
JUnit unit test
全上链哈希游戏dapp系统定制(方案设计)
图的基本概念以及相关定义
Berkeley, MIT, Cambridge, deepmind et d'autres grandes conférences en ligne: vers une IA sûre, fiable et contrôlable
传统的IO存在什么问题?为什么引入零拷贝的?
Packaging_ Conversion between basic type and string type