golang sqlx catch errors

(*-*)浩
Release: 2019-12-14 11:57:19
Original
2800 people have browsed it

golang sqlx catch errors

sqlxThis third-party library is indeed much more fun to use. Here are the learning and usage experiences

Installation:

Use commands (Recommended learning: Go )

go get github.com/jmoiron/sqlx
Copy after login

## Introduction:

The general idea is that sqlx is an extension of golang's standard database/sql. The interface using sqlx is no different from the original interface method, but has the following extensions:

1. Row records can be mapped such as struct (embedded struct Also supported), map and slices <--This is exactly the effect I wanted before

2. Supports the use of named parameters in prepared statements, and adds many extensions to the built-in database/sql package. Simplify the writing of database operation code.

3. Get and Select query results to struct/slice are faster

sqlx has also added many interfaces to facilitate developers to use, which will be discussed later.

package main
 
import (
	"database/sql"
	_"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"fmt"
)
 
type Student struct {
	Id         int    `db:"id"`
	Name       string `db:"name"`
	Nick       string `db:"nick"`
	Country    string `db:"country"`
	Province   string `db:"province"`
	City       string `db:"city"`
	ImgUrl     string `db:"img_url"`
	Status     int    `db:"status"`
	CreateTime string `db:"create_time"`
}
 
func main()  {
	dns := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", dbuser, dbpwd, dbhost, dbname)
	db, err := sqlx.Connect("mysql", dns)
	if err != nil {
        log.Fatalln(err)
	}
	defer db.Close()
 
	tx := db.MustBegin()
	tx.MustExec(`INSERT INTO student VALUES (&#39;1&#39;, &#39;Jack&#39;, &#39;Jack&#39;, &#39;England&#39;, &#39;&#39;, &#39;&#39;, &#39;http://img2.imgtn.bdimg.com/it/u=3588772980,2454248748&fm=27&gp=0.jpg&#39;, &#39;1&#39;, &#39;2018-06-26 17:08:35&#39;);`)
	tx.MustExec(`INSERT INTO student VALUES (&#39;2&#39;, &#39;Emily&#39;, &#39;Emily&#39;, &#39;England&#39;, &#39;&#39;, &#39;&#39;, &#39;http://img2.imgtn.bdimg.com/it/u=3588772980,2454248748&fm=27&gp=0.jpg&#39;, &#39;2&#39;, null);`)
	err = tx.Commit()
	if err != nil {
		log.Fatalln(err)
	}
 
}
Copy after login

The above is the detailed content of golang sqlx catch errors. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!