search
HomeSystem TutorialMACHow to use Golang with MySQL

This tutorial guides you through connecting your Golang projects to MySQL databases using the go-sql-driver/mysql driver. We'll cover driver installation, database connection, and basic database operations with practical examples.

Prerequisites: Ensure MySQL is installed and running. Verify this by executing mysql --version in your terminal. The output should display your MySQL version.

How to use Golang with MySQL

Installing the Go MySQL Driver:

Install the necessary driver using:

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

While other drivers exist, this is a popular and well-maintained choice. Refer to its GitHub page for detailed information.

Project Setup:

Create your Golang project directory. If not working within your Go installation directory, use these commands to initialize a Go module:

go mod init test-sql go mod tidy

This generates go.mod and go.sum files, essential for managing dependencies.

Connecting to MySQL:

Create a main.go file and add the following code:

package main

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

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/test")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    fmt.Println("Successfully connected to MySQL!")
}</your_mysql_password>

Remember to replace <your_mysql_password></your_mysql_password> with your actual MySQL database password. We recommend using a password manager for secure storage.

Use a code editor (like CodeRunner) to write and run this code. After saving, navigate to the project directory in your terminal and run:

go run main.go

A "Successfully connected to MySQL!" message confirms a successful connection.

How to use Golang with MySQL

Creating a MySQL Database:

For this tutorial, we'll use a database management tool like TablePlus to create a database (e.g., "123begin") and a table (e.g., "testtable2"). Adapt the following examples to your specific database and table names.

How to use Golang with MySQL

Database Operations:

Inserting Data:

This code inserts data into your table:

package main

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

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    insert, err := db.Query("INSERT INTO testtable2 VALUES('23')")
    if err != nil {
        panic(err.Error())
    }
    defer insert.Close()
    fmt.Println("Data inserted successfully!")
}</your_mysql_password>

Run go run main.go to execute the insertion.

How to use Golang with MySQL

Querying Data:

This code retrieves data from your table:

package main

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

type Testtable2 struct {
    id int `json:"id"`
}

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    results, err := db.Query("SELECT id FROM testtable2")
    if err != nil {
        panic(err.Error())
    }
    defer results.Close()
    for results.Next() {
        var testtable2 Testtable2
        err = results.Scan(&testtable2.id)
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}</your_mysql_password>

Run go run main.go to execute the query. The output should show the inserted data.

How to use Golang with MySQL

Troubleshooting:

  • Incorrect Directory: Ensure you're running go run main.go from the correct project directory. Use cd to navigate.
  • Missing go.mod/go.sum: If these files are missing, re-run the go mod init and go mod tidy commands.
  • MySQL Errors: Consult MySQL's official documentation for error resolution.

This enhanced tutorial provides a clearer, more concise, and step-by-step guide to connecting Golang to MySQL. Remember to replace placeholder values with your actual credentials and database information. Using tools like CodeRunner, TablePlus, SnippetsLab, and Secrets can streamline your workflow.

The above is the detailed content of How to use Golang with MySQL. 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
How to downgrade from macOS MontereyHow to downgrade from macOS MontereyApr 14, 2025 am 11:31 AM

This guide explains how to safely downgrade from macOS Monterey to Big Sur. Major macOS updates, especially betas, can introduce problems like incompatibility, speed issues, or missing features. This article provides a step-by-step process using a f

How to delete iOS apps from Mac with M1How to delete iOS apps from Mac with M1Apr 14, 2025 am 11:26 AM

Since Apple's first iPad was released in 2010, it has begun designing its own chips for its devices. The latest iteration of chips is the Apple A15 bionic chip on the iPhone 13. However, for Mac, the first Apple self-developed chip, the Apple M1, was not released until 2020 with the MacBook Air, Mac mini and MacBook Pro. In 2021, the 24-inch iMac followed closely, followed by improvements on the 14-inch and 16-inch MacBook Pro (as the Apple M1 Pro and A

How to Inspect Element on Mac (Quick tips)How to Inspect Element on Mac (Quick tips)Apr 14, 2025 am 11:06 AM

Mastering Webpage Inspection on Mac: A Comprehensive Guide This guide provides a detailed walkthrough of using the Inspect Element feature on Mac browsers (Safari, Chrome, and Firefox) to examine and modify webpage elements. Whether you're a designe

How to fix memory leaks MontereyHow to fix memory leaks MontereyApr 14, 2025 am 11:03 AM

macOS Monterey memory leak problem and solution Recently, a serious problem has occurred on macOS Monterey system that has troubled many users - a memory leak bug. Some applications consume a lot of memory (RAM), causing the system to pop up a warning of "out of application memory". This article will explain the severity of this problem and the solution. How memory leaks affect your work Before discussing memory leaks, let's briefly explain what memory is and why we need to pay attention to it. Each Mac has a certain amount of memory, also known as RAM, which enables the Mac to run a certain number of tasks simultaneously. Have you noticed that when you open many tabs and apps, your Mac starts lagging

How to create a new user on MacHow to create a new user on MacApr 14, 2025 am 10:52 AM

This guide shows you how to easily create and manage multiple user accounts on your Mac, keeping your files organized and your system running smoothly. I'll cover different account types and offer tips for optimizing performance with multiple users.

The best gaming VPNs for speed and securityThe best gaming VPNs for speed and securityApr 14, 2025 am 10:48 AM

Online gaming: Conquer lag and geo-restrictions with the right VPN Frustrated by lag, disconnections, and geo-restrictions ruining your online gaming experience? This guide explores the best VPNs for enhancing your gameplay, based on thorough resear

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.