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!

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

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

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

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

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.

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


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

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.