Go Language Web Development (6) use go to connect MySQL database operations

Source: Internet
Author: User

We use Https://github.com/Go-SQL-Driver/MySQL as the driver for Go connection MySQL, and perform database operation exercises.

(1) Import Database driver

import (   _"github.com/Go-SQL-Driver/MySQL")

The meaning of using _ here is to introduce the following package names instead of directly using the functions, variables, and other resources defined in the package. In the event of a failure to import, we can resolve it in the following way (for example, Window System)

windows+R 打开cmd,输入go get github.com/vmihailenco/redis ,回车之后会自动下载项目到GOPATH中的src目录下,然后刷新IDE。

(2) Database connection
Use SQL. Open for opening a registered database driver, there are several ways to connect, as shown below, generally we choose the second way

user@unix(/path/to/socket)/dbname?charset=utf8user:password@tcp(localhost:3306)/dbname?charset=utf8user:password@/dbnameuser:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname

(3) Increase and deletion check operation

Package Mainimport ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql") var (dbhostsip = "localhost:3306" D Busername = "root" Dbpassword = "123456" DBName = "Localmysql") func main () {//Connect to database Db,err: = SQL. Open ("MySQL", dbusername+ ":" +dbpassword+ "@tcp (" +dbhostsip+ ")/" +dbname "Checkerr (ERR) Insert (db)//Close database connection db. Close ()}//insert Demofunc Insert (db *sql. db) {//Prepare insert operation Stmt,err: = db.   Prepare ("INSERT User (User_name,user_age,user_sex) VALUES (?,?,?)") Checkerr (ERR)//Perform insert operation Res,err: = stmt. Exec ("Limao", 26,2) Checkerr (ERR)//Returns the most recent self-increment primary key ID Id,err: = Res. Lastinsertid () fmt. Println ("Lastinsertid:", id)}//queries demofunc query (DB *sql. db) {//rows: Returns the result set of the query operation Rows,err: = db. Query ("SELECT * from User") Checkerr (ERR)//First step: Receives the field name queried in the database table, returns a string array slice columns, _: = Rows. Columns ()///Columns: [user_id user_name User_age User_sex]//construct Scanargs, values two arrays based on the length of a string array slice, Each value of the Scanargs points to the address of the values corresponding to Scanargs: = Make ([]interface{}, Len (columns) Values: = Make ([]interface{}, Len (columns)) for I: = range values {scanargs[i] = &values[i]} for RO Ws. Next () {//To copy the address of the queried field name to the Scanargs array err = rows.      Scan (Scanargs ...) Checkerr (ERR)//Save row data to the record dictionary record: = Make (map[string]string) for I, col: = range values {if c OL = nil {//Field name = Field Information Record[columns[i]] = string (col. ([]byte))}} FMT. Println (record)}}//update Demofunc Update (DB *sql. db) {//Prepare update operation Stmt1,err: = db. Prepare ("UPDATE user SET user_age=?,user_sex=?")   WHERE user_id=? ") Checkerr (ERR)//Perform update operation res1, err: = Stmt1. Exec (2, 1) checkerr (ERR)//query update how many information num, err: = Res1. Rowsaffected () Checkerr (err) fmt. PRINTLN (num)}//remove Demofunc Remove (db *sql. db) {//Ready to delete operation stmt, err: = db. Prepare (' Delete from user WHERE user_id=? ') Checkerr (ERR)//Perform delete operation res, err: = stmt. Exec (1) checkerr (ERR)//query deletes how many messages num, err: = Res. Rowsaffected () Checkerr (err) FMT. PRINTLN (num)}//check error message func Checkerr (err error) {if err! = Nil {panic (err)}}

Summarize:
Db. The Prepare () function is used to return the SQL operation that is ready to be executed and then return to the ready execution state.
Db. The Query () function is used to directly execute SQL to return the rows result.
stmt. The Exec () function is used to execute stmt prepared SQL statements.
We can see that the parameters we pass in are all =? corresponding data, so that the way to do this can prevent SQL injection to some extent.

Reference article: http://www.01happy.com/golang-mysql-demo/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.