How 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.
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.
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.
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.
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.
Troubleshooting:
-
Incorrect Directory: Ensure you're running
go run main.go
from the correct project directory. Usecd
to navigate. -
Missing
go.mod
/go.sum
: If these files are missing, re-run thego mod init
andgo 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Mac Screen Recording: Easily capture windows, areas and drop-down menus The screenshot tool (Command Shift 5) that comes with Mac systems can record full screen or selected areas, but cannot record specific application windows separately. At this time, more powerful tools are needed to complete the task. This article will introduce several ways to help you record your Mac windows as easily as a professional. Record the application window separately Record a single window to avoid cluttered desktop backgrounds and create more professional and prominent images and videos. Here are some excellent screen recording applications: Function comparison Gifox CleanShot X Dropshare Record a specific window ✓ ✓ ✓

macOS version history macOS 15 Sequoia, September 16, 2024macOS 14 Sonoma,September 26, 2023 macOS 13 Ventura,October 25, 2022

You can’t avoid working with PDFs. But what you can avoid is having problems with them. Intractable as they seem, PDFs are actually pretty easy to deal with – not without help, of course. When it comes to making changes in your docs,Nitro PDF Pr

The market for AI-powered writing assistants is expected to grow rapidly, reaching approximately $6.5 billion by 2030. Since AI writing assistants are here to stay, it's important to learn about the best tools in the industry. In this article, w

This guide shows you how to refresh various aspects of your Mac, from web pages to the desktop and Messages. Let's dive in! Refreshing Web Pages on Your Mac For a quick refresh, the easiest method is using the keyboard shortcut Command R. This wor

Converting color PDFs to grayscale or black and white can effectively reduce file size, save printing costs, or facilitate previewing. This article will introduce the use of two methods of using Mac's own tools and third-party applications to achieve PDF color conversion. Grayscale images contain a variety of shades of gray from white to black, while true black and white images have only two colors: pure black and pure white. Therefore, for printed documents containing content other than simple text, grayscale is usually the preferred color format. Save PDFs to black and white instead of grayscale, the file size will decrease significantly, but the appearance of all objects except text will change. Therefore, converting PDFs from color to grayscale is usually a safer choice. Method 1: Use Nitro PDF Pro Nitro PD
