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!

Apple has released a second Release Candidate (RC) build of macOS Sequoia 15.4 for its beta testing program. This follows the initial release candidate builds of Sequoia 15.4, iOS 18.4, and iPadOS 18.4, released just days prior. Release Candidates a

VirtualBuddy: Easily virtualize macOS and Linux on Apple Silicon Mac VirtualBuddy provides a simple and fast way to virtualize macOS (and Linux) on any Apple Silicon Mac, providing developers, enthusiasts, and curious users with a way to easily run multiple instances of macOS. VirtualBuddy is fast, performs well, and it is free and open source, so you can easily explore the virtual machine world without any commitment, just prepare enough disk storage and bandwidth to set up a macOS or Linux virtual machine. Whether it is testing different versions

Buying a used Mac on a budget? This guide ensures you avoid a lemon. We'll cover essential checks before you buy, including diagnostics you can perform on the spot. Remember to bring a bootable macOS USB drive and headphones. Step 1: Physical Insp

How long does it take to update the MacOS system software? Why does it take so long to update? Many Mac users will have this question when they see the software update of the new MacOS system. Both of these questions are very reasonable, and it is important to remember that the answers may vary. However, with modern MacOS, you can make a fairly accurate estimate of the time it takes to install updates to your MacOS system. Let's dive into this topic so you can better understand and prepare to install MacOS updates on your Mac. How long does it take for MacOS updates to be downloaded, installed and completed? MacOS updates can take between 15-20 minutes to several hours to complete, especially if you are considering downloading updates and installing updates to completion

Understanding MacBook Battery Life: Maximizing Your Mac's Power Concerned about your MacBook's battery performance, or planning a purchase? This guide clarifies MacBook battery lifespan and offers tips for extending it. Most Mac batteries endure appr

Although the Safari browser under the Mac system is excellent, it is not perfect. Safari users occasionally encounter situations where the page refreshes and displays an error message "This page has reloaded because of a problem". You may also see variant information like "repeated problems". Since the error message is quite general, you may be wondering the root cause of the error in Safari and how to fix this on your Mac. Causes causing Safari for Mac to have a "This web page reloaded because a problem occurred" error Usually, if there is a memory problem, a website crash, or an incompatible with Safari, a software error, or other similar issues, you will see this error message in Safari on your Mac

Nostalgic Mac users may remember an interesting application in the classic Mac OS system: it will place a pair of moving eyes in the Mac menu bar and move with your cursor. While classic Mac OS is long gone, you can still experience this fun on a modern Mac, just use an app called "Googly Eyes". Google Eyes resides in your Mac menu bar, and its pupils will follow your cursor like an older version of the app. When clicking on the mouse/trackpad, the little eyes will blink. Will this revolutionize your computing experience? Probably not. But is it interesting? Absolutely fun! Sometimes, just being fun is enough, right? So, enjoy it, in your Ma

Apple has released macOS Sonoma 14.7.5 and macOS Ventura 13.7.5 security updates for Mac users running Sonoma and Ventura operating systems. These updates focus on security patches and do not include other new features available in the latest macOS Sequoia 15.4 update (sequoia 15.4 update is released simultaneously). Additionally, you'll find software updates for new and older iPhones and iPads, as well as updates for Apple TV, Apple Watch, and Apple Vision Pro


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

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
