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

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

With the support of Apple devices' interconnected ecosystem, managing and synchronizing your Apple devices has become a breeze. Unlock Mac with Apple Watch? Simple! (If you haven't set this unlocking method yet, you should really try it, it's very time-saving). Can you pay with Apple Watch without using iPhone? Apple can handle it easily! Today we will focus on how to download the Spotify playlist to an Apple Watch and play without an iPhone. Spoiler: This is possible. How to use Spotify on Apple Watch: A quick overview Let's dive into the key issues and their solutions directly. If this form helps you, that would be great! If you

When you see the message "Your screen is being monitored", the first thing you think of is someone hacking into your computer. But that's not always the case. Let's try to find out if there are any issues that need you to worry about. Protect your Mac With Setapp, you don't need to worry about choosing a tool to protect your computer. You can quickly form your own suite of privacy and security software on Setapp. Free Trial Security Test What does "Your screen is being monitored" mean? There are many reasons why there is a Mac lock screen message that appears with “Your screen is being monitored”. You are sharing the screen with others You are recording the screen You are using AirPlay You are using some apps that try to access your screen Your computer is infected with evil

After upgrading to the latest macOS, does the Mac run slower? Don't worry, you are not alone! This article will share my experience in solving slow Mac running problems after upgrading to macOS Sequoia. After the upgrade, I can’t wait to experience new features such as recording and transcription of voice notes and improved trail map planning capabilities. But after installation, my Mac started running slowly. Causes and solutions for slow Mac running after macOS update Here is my summary of my experience, I hope it can help you solve the problem of slow Mac running after macOS Sequoia update: Cause of the problem Solution Performance issues Using Novabe

macOS WindowServer: Understanding High CPU Usage and Solutions Have you noticed WindowServer consuming significant CPU resources on your Mac? This process is crucial for your Mac's graphical interface, rendering everything you see on screen. High C

Mac mail synchronization failed? Quick solution! Many Mac users rely on the included Mail app because it is simple and convenient. But even reliable software can have problems. One of the most common problems is that Mail cannot be synced, resulting in recent emails not being displayed. This article will guide you through email synchronization issues and provide some practical tips to prevent such issues. How to refresh the Mail app on your Mac Operation steps Click the envelope icon Open the Mail app > View > Show Tab Bar > Click the Envelope icon to refresh. Use shortcut keys or menu options Press Shift Command N. Or open the Mail app

This guide explains how to convert between Live Photos, videos, and GIFs on iPhones and Macs. Modern iPhones excel at image processing, but managing different media formats can be tricky. This tutorial provides solutions for various conversions, al
