Install MySQL driver: Execute go get -u github.com/go-sql-driver/mysql; 2. Use the database/sql package to establish a connection with DSN (such as username:password@tcp(localhost:3306)/dbname), and verify the connection through db.Ping(); 3. It is recommended to configure connection pool parameters such as SetMaxOpenConns, SetMaxIdleConns and SetConnMaxLifetime to optimize performance; 4. Use db.Query to read data with rows.Scan when executing queries; 5. Pay attention to common problems: Make sure the database exists, the username and password are correct, and use an underscore prefix when importing the driver to trigger initialization. The complete process includes importing drivers, building DSNs, opening databases, testing connections, executing queries and properly handling errors, and successfully connecting and operating the MySQL database.
Connecting to a MySQL database in Go is straightforward using the database/sql
package and a MySQL driver like go-sql-driver/mysql
. Below is a practical example showing how to set up and use a connection.

? 1. Install the MySQL Driver
First, install the MySQL driver:
go get -u github.com/go-sql-driver/mysql
? 2. Basic Connection Example
Here's a simple Go program that connects to a MySQL database and pings it to verify the connection:

package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" // Import the MySQL driver ) func main() { // Replace with your actual connection details dsn := "username:password@tcp(localhost:3306)/your_database_name" db, err := sql.Open("mysql", dsn) if err != nil { log.Fatal("Failed to open database:", err) } defer db.Close() // Test the connection err = db.Ping() if err != nil { log.Fatal("Failed to ping database:", err) } fmt.Println("Connected to MySQL database!") }
? Key Details
DSN (Data Source Name) : The string
username:password@tcp(localhost:3306)/dbname
is the DSN.- Use
tcp(localhost:3306)
for local connections. - You can add parameters like
parseTime=true
if you're working with time fields:dsn := "username:password@tcp(localhost:3306)/your_db?parseTime=true"
- Use
sql.Open
doesn't connect immediately — it just initializes the database handle.db.Ping()
actually tests the connection.
? 3. Using Connection Settings (Optional but Recommended)
For production, configure connection pooling:
db.SetMaxOpenConns(25) db.SetMaxIdleConns(25) db.SetConnMaxLifetime(time.Minute * 5)
These help avoid resource exhaustion and improve performance.
? 4. Example Query
Once connected, you can run queries:
var id int var name string rows, err := db.Query("SELECT id, name FROM users") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { err := rows.Scan(&id, &name) if err != nil { log.Fatal(err) } fmt.Printf("ID: %d, Name: %s\n", id, name) }
?? Common Issues
- "Unknown database" : Make sure the database exists.
- "Access denied" : Check username, password, and MySQL user privileges.
- Driver not found : Ensure you imported the driver with
_ "github.com/go-sql-driver/mysql"
— the underscore is cruel.
Basically, that's all you need to get started. The pattern is:
- Import driver
- Build DSN
-
sql.Open
-
db.Ping
- Use
db
for queries
Not complicated — just pay attention to the DSN format and error handling.
The above is the detailed content of go by example connecting to a mysql database. 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

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

To import local packages correctly, you need to use the Go module and follow the principle of matching directory structure with import paths. 1. Use gomodinit to initialize the module, such as gomodinitexample.com/myproject; 2. Place the local package in a subdirectory, such as mypkg/utils.go, and the package is declared as packagemypkg; 3. Import it in main.go through the full module path, such as import "example.com/myproject/mypkg"; 4. Avoid relative import, path mismatch or naming conflicts; 5. Use replace directive for packages outside the module. Just make sure the module is initialized

How to use maps in Go includes: 1. Use make to create empty maps or literal initialization; 2. Access, modify and add elements through keys; 3. Use delete function to delete key-value pairs; 4. Check whether the key exists through value, ok:=m[key]; 5. Use len to get length; 6. Use forrange to traverse, the order is uncertain; 7. The key must be a comparable type, such as string, int, etc., and slice, map or func is not available; 8. Note that nilmap cannot be assigned directly, and it needs to be initialized first, and map is not concurrently safe. Multiple goroutine scenarios need to be locked or sync.Map is used. Mastering these core operations can meet daily development needs

BuildconstraintsinGoarecommentslike//go:buildthatcontrolfileinclusionduringcompilationbasedonconditionssuchasOS,architecture,orcustomtags.2.TheyareplacedbeforethepackagedeclarationwithablanklineinbetweenandsupportBooleanoperatorslike&&,||,and

When you cannot connect to the MySQL database, you should first check the connection string format and driver version. 1. Check whether the connection string format is correct. Common errors include port number, database name, parameter symbol errors and driver prefix errors. It is recommended to use the generation tool to verify the format and pay attention to escaping special characters; 2. Ensure that the correct JDBC or database driver is used, different drivers are used in different languages. Pay attention to version compatibility, dependency configuration and driver class name changes, and check the log to confirm whether the driver is loading successfully; 3. Check remote access permissions and firewall settings, including MySQL user permissions, bind-address configuration and server firewall rules, and need to open port 3306 and remote access permissions; 4. Use a simple test program to quickly verify the connection.

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

The core methods for realizing MySQL data blood ties tracking include: 1. Use Binlog to record the data change source, enable and analyze binlog, and trace specific business actions in combination with the application layer context; 2. Inject blood ties tags into the ETL process, and record the mapping relationship between the source and the target when synchronizing the tool; 3. Add comments and metadata tags to the data, explain the field source when building the table, and connect to the metadata management system to form a visual map; 4. Pay attention to primary key consistency, avoid excessive dependence on SQL analysis, version control data model changes, and regularly check blood ties data to ensure accurate and reliable blood ties tracking.

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum
