TL;DR:

  • Set up the Go MySQL driver: go get -u github.com/go-sql-driver/mysql.
  • Hook up with your database utilizing sql.Open and check with db.Ping.
  • Use db.Question, db.Exec, and db.Scan for insert, learn, replace, and delete operations.
  • Be sure that your MySQL server is working and your connection string is appropriate.
  • Use CodeRunner to write down and check your Go code, SnippetsLab to arrange snippets, Secrets and techniques 4 to retailer passwords safely, and TablePlus to handle databases with ease.

Searching for the perfect database to make use of in your Golang tasks? MySQL is likely one of the hottest instruments for working with SQL databases. Is it the perfect one for you? The one technique to know is to strive it out.

On this article, I’ll stroll you thru how to connect with MySQL databases utilizing Go, arrange your surroundings for easy integration, and run fundamental database operations with hands-on Go + MySQL examples.

Getting began with Go MySQL driver

Listed here are the primary steps you have to take:

  1. Be sure you have MySQL in your machine by working mysql –version command in Terminal.
  2. You probably have MySQL, you may see the MySQL model printed in your Terminal window.
  3. Subsequent, run the set up command for the Golang MySQL driver: go get -u github.com/go-sql-driver/mysql.

run mySQL

You don’t have to make use of this particular Go MySQL driver, but it surely’s a well-liked one, so we’re utilizing it for our tutorial. You will discover detailed details about this driver on its web page on GitHub.

Now, let’s hook up with MySQL.

Now, let’s hook up with MySQL

Create your utility within the folder the place you will have all of your Golang set up recordsdata, or run: 

  • go mod init test-sql
  • go mod tidy

This lets you run your Go app in a folder apart from the one you’ve put in Go in.

With that out of the best way, you are prepared to attach. Create a major.go file and insert the next code:

bundle major
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    // Exchange 'yourpassword' along with your precise MySQL root password
    dsn := "root:yourpassword@tcp(127.0.0.1:3306)/check"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    // Confirm the connection is legitimate
    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }
    fmt.Println("Success!")
}

Ensure that the check database exists in your MySQL server. If it does not, you’ll be able to create it utilizing the MySQL command-line interface: CREATE DATABASE check;.

You may write this code utilizing any code editor you want. I exploit CodeRunner, a fast code editor with helpful syntax highlighters, IDE options, and assist for over 25 languages, together with Golang. Simply copy the above code and insert your MySQL database password on this line:

“root:@tcp(127.0.0.1:3306)/check”).

code editor

When you do that, you are able to run your Go utility in Terminal. First, transfer to the folder containing your major.go program utilizing the change listing command cd:

run your Go application in Terminal

Subsequent, kind go run major.go. Your program will print “Success!” on the display if all the things runs easily.

Connecting your Go utility to MySQL

To attach your Go utility to MySQL:

  1. Create a brand new Go challenge folder in the event you don’t have one already.
  2. Add the go-sql-driver/mysql bundle to your Go challenge utilizing go get -u github.com/go-sql-driver/mysql. If you happen to’re utilizing a unique database system, modify the motive force identify (the “mysql” half) accordingly. 
  3. Write a Go program to connect with MySQL utilizing this code:
import (
    "database/sql"
    "fmt"
    "log"
    "github.com/go-sql-driver/mysql"
)
func major() {
    cfg := mysql.Config{
        Consumer:                 "consumer",
        Passwd:               "password",
        Internet:                  "tcp",
        Addr:                 "localhost:3306",
        DBName:               "database",
        AllowNativePasswords: true,
    }
    db, err := sql.Open("mysql", cfg.FormatDSN())
    if err != nil {
        log.Deadly(err)
    }
    defer db.Shut()
    if err = db.Ping(); err != nil {
        log.Deadly(err)
    }
    fmt.Println("Efficiently related to MySQL!")
}

4. Exchange consumer:password@tcp(host:port)/database along with your MySQL connection particulars.

5. Save the code to an executable file and run it utilizing the command go run major.go.

To efficiently join your Go utility to MySQL, be sure that your MySQL consumer is correctly put in and configured. Handle dependencies in your Go challenge utilizing Go modules, institute thorough error dealing with, and use safe strategies to retailer and transmit MySQL secrets and techniques.

Establishing your MySQL database for Golang

Earlier than you arrange your MySQL database for Golang, you first want to put in MySQL utilizing these steps:

  1. Obtain the set up bundle from the official MySQL web site.
  2. Open the bundle and comply with the set up wizard directions. 
  3. Set a password for the foundation consumer if requested.
  4. Shut the wizard as soon as the set up is completed. 

You too can set up MySQL utilizing Homebrew if it is in your Mac. Merely open Terminal and kind the command brew set up mysql. To confirm your MySQL set up, kind the Terminal command mysql –version and run the command mysql -u root -p to start out utilizing the server. 

My SQL

Working with a MySQL database

Now that now we have our desk, let’s attempt to insert some knowledge: a database object.

This is the code for inserting an object right into a desk in your database:

bundle major
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    db, err := sql.Open("mysql", "root:<password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    insert, err := db.Question("INSERT INTO testtable2 VALUES('23')")
    if err !=nil {
        panic(err.Error())
    }
    defer insert.Shut()
    fmt.Println("Yay, values added!")
}

Add this code to your major.go file. You may copy your earlier code to SnippetsLab to entry it for different tasks.

Now, run go run major.go command in Terminal within the folder along with your Go challenge. If all the things goes proper, you must have Yay, values added! printed again:

run main.go command in Terminal

With the brand new worth added, we are able to have a Golang app do an SQL DB question to test that the worth has certainly been added to the desk.

Right here’s the code I used for this:

bundle major
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
kind Testtable2 struct {
    id int `json:"id"`
}
func major() {
    db, err := sql.Open("mysql", "root:<password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    outcomes, err := db.Question("SELECT id FROM testtable2")
    if err !=nil {
        panic(err.Error())
    }
    for outcomes.Subsequent() {
        var testtable2 Testtable2
        err = outcomes.Scan(&testtable2.id)
        if err !=nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}

Exchange testtable2, 123begin, and id with respective values in your database desk, database identify, and the column you are querying.

Run go run major.go in Terminal:

santae bash

Now we have 23 printed again to us, which is the worth we’ve inserted into our desk within the earlier step, so our question has been successful.

Executing SQL queries in Golang

Subsequent, I will present you the way to do that.

Insert operation

To insert an object into your MySQL desk utilizing Go:

  1. Add this code to your major.go file:

bundle major
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    db, err := sql.Open("mysql", "root:<password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    insert, err := db.Question("INSERT INTO testtable2 VALUES('23')")
    if err !=nil {
        panic(err.Error())
    }
    defer insert.Shut()
    fmt.Println("Yay, values added!")
}

2. Run major.go in Terminal, and you may obtain the road “Yay, values added” or what you changed it with if all the things goes properly.

Only a reminder: 23 is the worth we added to the database desk.

Learn operation

To learn values in a MySQL desk utilizing Go:

  1. Add this code to your major.go file:

bundle major
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
kind Testtable2 struct {
    id int `json:"id"`
}
func major() {
    db, err := sql.Open("mysql", "root:<password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    outcomes, err := db.Question("SELECT id FROM testtable2")
    if err !=nil {
        panic(err.Error())
    }
    for outcomes.Subsequent() {
        var testtable2 Testtable2
        err = outcomes.Scan(&testtable2.id)
        if err !=nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}

2. Exchange testtable2, 123begin, and id with respective values in your database desk, database identify, and the column you wish to learn.

3. Run major.go in Terminal, and you may obtain the values within the desk fields referenced if all the things is completed proper.

On this case, the worth returned is 23 because it’s what was inserted into the desk.

Replace operation

To replace a MySQL desk utilizing Go:

  1. Add this code to your major.go file:

bundle major
import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    // Exchange along with your precise DB credentials
    dsn := "username:password@tcp(127.0.0.1:3306)/yourdbname"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatalf("Error opening DB: %v", err)
    }
    defer db.Shut()
    // Test DB connection
    if err := db.Ping(); err != nil {
        log.Fatalf("Error pinging DB: %v", err)
    }
    // Instance: Replace consumer e-mail the place user_id = ?
    question := "UPDATE customers SET e-mail = ? WHERE user_id = ?"
    // Parameters
    newEmail := "[email protected]"
    userID := 1
    // Execute the question
    outcome, err := db.Exec(question, newEmail, userID)
    if err != nil {
        log.Fatalf("Error updating report: %v", err)
    }
    // Affected rows
    rowsAffected, err := outcome.RowsAffected()
    if err != nil {
        log.Fatalf("Error getting rows affected: %v", err)
    }
    fmt.Printf("Replace profitable, %d row(s) affected.n", rowsAffected)
}

2. Exchange customers, e-mail, and user_id along with your desk and column names.

3. Run major.go in Terminal.

If all the things is completed proper, the desk fields talked about within the code needs to be up to date as instructed. 

Delete operation

To delete a row from a MySQL desk utilizing Go:

  1. Add this code to your major.go file:

bundle major
import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    // Exchange along with your precise DB credentials
    dsn := "username:password@tcp(127.0.0.1:3306)/yourdbname"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatalf("Failed to connect with DB: %v", err)
    }
    defer db.Shut()
    // Check the connection
    if err := db.Ping(); err != nil {
        log.Fatalf("Did not ping DB: %v", err)
    }
    // DELETE assertion with placeholder
    question := "DELETE FROM customers WHERE user_id = ?"
    // ID of the row to delete
    userID := 1
    // Execute the DELETE question
    outcome, err := db.Exec(question, userID)
    if err != nil {
        log.Fatalf("Did not delete report: %v", err)
    }
    // Test what number of rows had been affected
    rowsAffected, err := outcome.RowsAffected()
    if err != nil {
        log.Fatalf("Did not retrieve affected rows: %v", err)
    }
    fmt.Printf("Efficiently deleted %d row(s)n", rowsAffected)
}

2. Run major.go in Terminal.

If all the things is ready up appropriately, the desired row will likely be deleted from the desk.

Learn additionally:

Go MySQL driver points

When writing code, it’s straightforward for typos or incorrect instructions to sneak in.

One of the vital widespread errors is working go run major.go within the mistaken folder. Be sure you’re contained in the folder that comprises your Go challenge, or the app gained’t run.

Use the cd (change listing) command to navigate to the right folder. A fast trick: simply drag and drop the folder into your Terminal window after typing cd, then press Enter.

Additionally, your Go app gained’t run with out go.mod and go.sum. Run the ls command in Terminal to test that each recordsdata are in your folder. In the event that they’re lacking, create them utilizing the instructions talked about within the Getting began part above.

And in the event you assume you’ve run into an actual MySQL bug, you’ll be able to report it instantly on MySQL’s official bug report web page.

Ultimate ideas on tips on how to use Go together with MySQL

On this tutorial, I walked you thru tips on how to join your Golang app to a MySQL database utilizing the Go MySQL driver. I lined all the things from organising your database and putting in the motive force to working fundamental SQL operations like insert, learn, replace, and delete, all with actual, hands-on examples. By now, you must really feel assured constructing Go apps that work together easily with MySQL.

Alongside the best way, I used just a few instruments that made the method simpler and extra environment friendly. I wrote and examined code in CodeRunner, saved my snippets organized with SnippetsLab, saved database credentials securely utilizing Secrets and techniques 4, and managed my databases with TablePlus. These instruments helped streamline the workflow, they usually can do the identical for you.

All of those apps can be found by means of Setapp, a one-stop productiveness platform for Mac customers. With Setapp, you get entry to 260+ highly effective apps for growth, time administration, file group, and extra. You may strive it free for 7 days and see the way it suits your workflow.

FAQs

How do I set up MySQL for Golang?

To put in MySQL for Golang, open the bundle downloaded from the official MySQL web site and comply with the directions within the set up wizard. 

What’s the finest Go MySQL driver?

The very best Go MySQL driver is go-sql-driver/mysq. It is probably the most broadly used MySQL driver for Golang because it’s mild, quick, and doesn’t depend on C bindings for its native Go implementation. It allows connections through TCP/IPv4, Unix sockets, and TCP/IPv6, whereas routinely pooling connections and dealing with damaged ones. 

How do I insert knowledge into MySQL utilizing Golang?

To insert knowledge into MySQL utilizing Golang, add this code to your Go file major.go and run it in Terminal by coming into: 

go run major.go: 
bundle major
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func major() {
    db, err := sql.Open("mysql", "root:<password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Shut()
    insert, err := db.Question("INSERT INTO testtable2 VALUES('23')")
    if err !=nil {
        panic(err.Error())
    }
    defer insert.Shut()
    fmt.Println("Values so as to add")
}

While you run the Go file, it ought to return “Values so as to add” or what you substituted it with.

Why is my Golang MySQL connection failing?

Your Golang–MySQL connection is likely to be failing as a result of the MySQL server isn’t working or accessible, there are errors in your database names or connection values, or your file and folder paths are incorrect or damaged.

Von admin

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert