Install the driver

Like most programming languages, Golang doesn’t come with any database drivers. So we have to install the third party library first.

Golang has a database/ SQL package in it. Then I figured it out. The Database/SQL package provides a generic interface to guarantee SQL or SQL-like databases, which must be injected with a database driver.

Since I operate mysql database this time, the third-party library I use is:

Github.com/go-sql-driv…

Run the go get -u github.com/go-sql-driver/mysql command to install the MySQL driver for Golang

$Go get -u github.com/go-sql-driver/mysql go: Finding github.com/go-sql-driver/mysql v1.5.0 go: Downloading github.com/go-sql-driver/mysql v1.5.0 GO: Fully github.com/go-sql-driver/mysql v1.5.0Copy the code

Connecting to a Database

package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"fmt"
)

func main(a) {
	// Data source syntax: "User name: password @[connection mode](host name: port number)/ database name"
	dsn := "Root @ TCP (127.0.0.1:3306)/dianping"
	db, err := sql.Open("mysql", dsn)  The open() method does not actually establish a connection to the database, but only sets the parameters required for the connection
	iferr ! =nil {
		panic(err)
	}

	Err := db.ping () // Connect to the database
	defer db.Close()
}
Copy the code

Operating database

Mysql > create test table

create table test1(
    id int primary key.name varchar(10));Copy the code

add

sql:=Insert into test1 values (1,' kaka ')"
    result,_:=db.Exec(sql)      / / SQL execution
    num,_:=result.RowsAffected(); // Get the number of affected rows
    fmt.Println("Number of rows affected:",num)
Copy the code

The query

Rows,_:= db.query ("select * from test1") for rows.next (){rows.Scan(&id,&name) FMT.Println(id,"--",name)}Copy the code