Home >Database >Mysql Tutorial >MySQL database programming using Go language: from beginner to proficient

MySQL database programming using Go language: from beginner to proficient

WBOY
WBOYOriginal
2023-06-17 19:16:581414browse

With the development of the Internet, databases have become one of the main ways to store data. As an open source, easy-to-use and powerful relational database, MySQL has become the standard for today's Internet development. As a fast and efficient programming language, Go language is favored by more and more developers. So how to combine the two for MySQL database programming? This article will explain it to you from beginner to master.

1. Install and set up the Go language development environment

The Go language official website provides installation programs suitable for various operating systems. You can choose the appropriate installation program for installation according to your own operating system version. . After the installation is complete, you need to set the environment variables related to the Go language. The specific operations are as follows:

1. Set GOROOT

GOROOT is the installation path of Go language. Under Windows system, you need to add the Go language installation path to the environment variable. Under other systems, you need to set GOROOT to the installation path of the Go language.

2. Set GOPATH

GOPATH is the working directory of the Go language, which is the path where Go code is stored. If GOPATH is not set, the Go language will create a new directory named Go in the current user's home directory by default and use it as GOPATH. Therefore, it is recommended to set GOPATH to prevent conflicts with directories used by other development languages.

2. Install MySQL

Since there is no built-in support for MySQL in the Go language, you need to use a third-party driver to access MySQL. Before using third-party drivers, you need to install the MySQL database. The installation method of the MySQL database is very flexible and will not be described here.

3. Install MySQL driver

There are many third-party MySQL drivers in Go language. Commonly used ones include go-sql-driver/mysql and mysql-orm. This article will use go- Taking sql-driver/mysql as an example, the following are the installation steps:

1. Enter the following command in the terminal or command line tool:

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

2. After the download is completed, import the module in the code:

import "github.com/go-sql-driver/mysql"

4. Connect to MySQL database

Before using the MySQL driver, you need to establish the corresponding connection. Next, we will demonstrate how to use Go language code to connect.

1. Create the main.go file

Create a new main.go file in the open text editor.

2. Import the necessary modules

Import the necessary modules at the beginning of the main.go file:

package main

import (

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

)

3. Establish a connection

Add the following code in the main.go file to establish a connection with the MySQL database:

func main() {

db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname?charset=utf8")
if err != nil {
    fmt.Println("open mysql failed,", err)
    return
}
defer db.Close()
fmt.Println("connect to mysql success")

}

Among them, username is the MySQL user name, password is the MySQL password, dbname is the database name to be connected, tcp is the protocol, 127.0.0.1 is the IP address, 3306 is the port number, charset The character set specified is utf8.

5. Execute SQL query and insert operations

After successfully connecting to the database, we can use Go language code to perform SQL query and insert operations. Below we will explain the query and insert operations separately.

1. Execute SQL query operations

It is extremely simple to execute SQL query operations using Go language code, and only requires a few lines of code to complete. For example, query all data in the user table:

func main() {

// 建立连接

rows, err := db.Query("SELECT * FROM user")
if err != nil {
    fmt.Println("query data failed,", err)
    return
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    var age int
    err := rows.Scan(&id, &name, &age)
    if err != nil {
        fmt.Println("get data failed,", err)
        continue
    }
    fmt.Println(id, name, age)
}

}

2. Perform SQL insertion operation

Use Go language code Performing SQL insert operations is also very simple and requires only a few lines of code to complete. For example, insert new data into the user table:

func main() {

// 建立连接

stmt, err := db.Prepare("INSERT INTO user(name, age) VALUES (?, ?)")
if err != nil {
    fmt.Println("prepare failed,", err)
    return
}
defer stmt.Close()

res, err := stmt.Exec("john", 29)
if err != nil {
    fmt.Println("insert data failed,", err)
    return
}

lastInsertId, err := res.LastInsertId()
if err != nil {
    fmt.Println("get last insert id failed,", err)
    return
}
fmt.Println("last insert id:", lastInsertId)
rowsAffected, err := res.RowsAffected()
if err != nil {
    fmt.Println("get rows affected failed,", err)
    return
}
fmt.Println("rows affected:", rowsAffected)

}

MySQL database programming using Go language is very easy to learn and use. If you master these After gaining knowledge, you can try more complex operations, such as transactions, connection pooling, etc. In short, through the explanation of this article, I believe that everyone has mastered the basic knowledge of the combination of Go language and MySQL database. I hope that everyone can give full play to their talents in the subsequent Go language development!

The above is the detailed content of MySQL database programming using Go language: from beginner to proficient. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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