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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

You’ve had your Mac for a few years, and you’re starting to feel the effects of your device aging—the battery doesn’t hold up as well as it used to. To avoid getting stuck with a dead Mac, you have no choice but to take your charger e

The Focus Modes functionality comes with several pre-set options such as Work, Driving, Sleep, and users are also free to create custom ones for any scenario imaginable. Should you find yourself not needing a multitude of Focus modes—whether because

If you trust Siri to accurately transcribe your speech into text and send it as a message, you can activate a setting that lets Siri send messages automatically from your iPhone without asking for confirmation first.With the confirmation feature enab

Apple has made available macOS Monterey 12.6.2 and macOS Big Sur 11.7.2 for users still operating on previous-generation Mac systems. These updates are offered independently of macOS Ventura 13.1.Both macOS Monterey 12.6.2 and macOS Big Sur 11.7.2 co

Some users of Mac computers running MacOS Sierra and MacOS High Sierra have reported issues when trying to log in to an Apple ID or iCloud via System Preferences, as well as problems accessing iCloud.com using Safari. In addition, Safari fails to loa

Creating a bootable macOS Ventura installer can be desirable for many advanced Mac users, whether to perform clean installations, install macOS Ventura 13 onto multiple machines without having to re-download the installer, to serve as a recovery boot

iOS 16 is now available for iPhone users, offering a solid update packed with practical features you're sure to enjoy.The most noticeable and exciting addition is the ability to personalize your lock screen. However, there are also plenty of smaller

Have you ever received a long audio message on your iPhone and while listening, the screen turns off, interrupting the playback and forcing you to start over? It's pretty frustrating, isn't it?Next time you receive a lengthy voice message on your iPh
