1024programmer Java Golang native sql operation Mysql database addition, deletion, modification and query

Golang native sql operation Mysql database addition, deletion, modification and query

To operate the mysql database in Golang, you first need to configure GOPATH in the current system, because you need to use the go get command to download the driver package to GOPATH for use.

First configure your GOPATH, execute the following command, Download and install the mysql driver. After the download is completed, it will be in the src/github.com directory under GOPATH

go get -u github.com/go-sql-driver/mysql

Then the local mysql service is started and a table is created as a test

DROP TABLE IF EXISTS `student`;
 CREATE TABLE `student` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(50) CHARACTER SET latin1 NOT NULL DEFAULT '',
   `age` tinyint(4) DEFAULT '0',
   PRIMARY KEY (`id`)
 ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Connect mysql database command

//mysql database, username: password @tcp connection: port 3306/test library?Character set utf8
 db, err := sql.Open("mysql", "root:root@tcp  (127.0.0.1:3306)/test?charset=utf8") //Returns the connection character, and err

Add, delete, modify and check code (import the mysql driver package and use the datebase/sql Open function to connect)

package main import ( "database/sql" // This is an abstraction layer package, such as distinguishing between mysql, orcal and other databases. Only this package cannot connect to mysql, and it also needs to be matched with the following mysql package
        "fmt" _ "github.com/go-sql  -driver/mysql" //Import mysql driver package
 ) func init() { } func main() {
     db, err := sql.Open("mysql", "root:root@tcp  (127.0.0.1:3306)/test?charset=utf8")
     if err != nil { panic(err) } //Add data
         stmt, err := db.Prepare(`INSERT student (name,age) values ​​(?,?)`) res, err := stmt.Exec("wangwu", 26) id, err := res.LastInsertId() fmt.Println("Auto-increment id=", id) //Modify data
         stmt, err := db.Prepare(`UPDATE student SET age=? WHERE id=?`) res, err := stmt.Exec(21,   5) num, err := res.RowsAffected() //Number of rows affected
  fmt.Println(num) //Delete data
         stmt, err := db.Prepare(`DELETE FROM student WHERE id=?`) res, err := stmt.Exec(5) num, err  := res.RowsAffected() fmt.Println(num) //Query data
     rows, err := db.Query("SELECT * FROM student") //--------Simple output line by line---start // for rows.Next() { //Go to the next level if the conditions are met// var id int // var name string // var age int // rows.Columns() // err = rows.Scan(&id, &name, &age) // fmt.Println(id) // fmt.Println(name) // fmt.Println(age) // } //--------Simple output line by line ---end //--------Traverse and put into map----start //Construct two arrays of scanArgs and values, each value of scanArgs  Points to the address of the corresponding value of values
     columns, _ := rows.Columns() scanArgs := make([]interface{}, len(columns)) values ​​:=  make([]interface{}, len(columns)) for i := range values ​​{ scanArgs[i]   span>= &values[i] } for rows.Next() { //will  Row data is saved to record dictionary
         err = rows.Scan(scanArgs...) record := make(map[string]string)   for i, col := range values ​​{ if col != nil { record[columns[i]]   = string(col.([]byte)) } } fmt.Println(record) } //  --------Traverse and put into map----end
 }

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/golang-native-sql-operation-mysql-database-addition-deletion-modification-and-query/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索