国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home System Tutorial MAC How to use Golang with MySQL

How to use Golang with MySQL

Apr 11, 2025 am 10:37 AM

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.

How to use Golang with MySQL

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.

How to use Golang with MySQL

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.

How to use Golang with MySQL

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.

How to use Golang with MySQL

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.

How to use Golang with MySQL

Troubleshooting:

  • Incorrect Directory: Ensure you're running go run main.go from the correct project directory. Use cd to navigate.
  • Missing go.mod/go.sum: If these files are missing, re-run the go mod init and go 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Save Battery on MacBook? How to Improve It? How to Save Battery on MacBook? How to Improve It? Jun 19, 2025 am 10:15 AM

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

How to Delete Focus Modes on iPhone & iPad How to Delete Focus Modes on iPhone & iPad Jun 18, 2025 am 10:40 AM

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

How to Automatically Send Messages with Siri from iPhone Without Confirmation How to Automatically Send Messages with Siri from iPhone Without Confirmation Jun 20, 2025 am 09:40 AM

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

macOS Monterey 12.6.2 & macOS Big Sur 11.7.2 Available with Security Fixes macOS Monterey 12.6.2 & macOS Big Sur 11.7.2 Available with Security Fixes Jun 14, 2025 am 09:32 AM

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

Fix iCloud Errors & “Can’t Establish Secure Connection with idmsa.apple.com” on MacOS Sierra & High Sierra Fix iCloud Errors & “Can’t Establish Secure Connection with idmsa.apple.com” on MacOS Sierra & High Sierra Jun 22, 2025 am 10:06 AM

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

How to Create a Bootable macOS Ventura USB Install Drive How to Create a Bootable macOS Ventura USB Install Drive Jun 14, 2025 am 09:46 AM

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

7 of the Best iOS 16 Features to Check Out Right Away 7 of the Best iOS 16 Features to Check Out Right Away Jun 22, 2025 am 09:56 AM

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

Listen to Long Audio Messages Easier on iPhone with This Trick Listen to Long Audio Messages Easier on iPhone with This Trick Jun 23, 2025 am 09:44 AM

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

See all articles