tencent cloud

TDSQL Boundless

Release Notes
Product Introduction
Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
Kernel Features
Kernel Overview
Kernel Version Release Notes
Functionality Features
Performance Features
Billing
Billing Overview
Purchase Method
Pricing Details
Renewal
Overdue Payments
Refund
Getting Started
Creating an Instance
Connect to Instances
User Guide
Data Migration
Data Subscription
Instance Management
Parameter Configuration
Account Management
Security Group
Backup and Restoration
Database Auditing
Tag Management
Use Cases
Technical Evolution and Usage Practices of Online DDL
Lock Mechanism Analysis and Troubleshooting Practices
Data Intelligent Scheduling and Related Practices for Performance Optimization
TDSQL Boundless Selection Guide and Practical Tutorial
Developer Guide
Developer Guide (MySQL Compatibility Mode)
Developer Guide (HBase Compatibility Mode)
Performance Tuning
Performance Tuning Overview
SQL Tuning
DDL Tuning
Performance White Paper
Performance Overview
TPC-C Test
Sysbench Test
API Documentation
History
Introduction
API Category
Making API Requests
Instance APIs
Security Group APIs
Task APIs
Backup APIs
Rollback APIs
Parameter APIs
Database APIs
Data Types
Error Codes
General Reference
System Architecture
SQL Reference
Database Parameter Description
TPC-H benchmark data model reference
Error Code Information
Security and Compliance
FAQs
Agreements
Service Level Agreement
Terms of Service
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Go

PDF
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-03-06 18:48:24

Using Go MySQL Driver

This document describes how to perform database operations on TDSQL Boundless using the MySQL driver for Go, including basic operations such as connecting to databases, creating tables, inserting data, updating data, and deleting data.

Install Driver

Before using the Go MySQL Driver, you need to install the driver first:
go get -u github.com/go-sql-driver/mysql

Basic Operations Sample

Connecting to the database

package main

import (
"database/sql"
"fmt"
"log"

_ "github.com/go-sql-driver/mysql"
)

func main() {
// Connect to the database
db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
log.Fatal(err)
}
defer db.Close()

// Test connection
err = db.Ping()
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MySQL database!")
}

Connection Pool Configuration

db.SetMaxOpenConns(25) // Maximum Open Connections
db.SetMaxIdleConns(5) // Maximum Idle Connections
db.SetConnMaxLifetime(5 * time.Minute) // Maximum connection lifetime

Creating a Table


query := `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`
_, err := db.Exec(query)
if err != nil {
log.Fatal(err)
}


Inserting Data

query := "INSERT INTO users (username, email) VALUES (?, ?)"


result, err := db.Exec(query, "john_doe", "john@example.com")
if err != nil {
log.Fatal(err)
}


id, err := result.LastInsertId()
if err != nil {
log.Fatal(err)
}

Updating Data

query := "UPDATE users SET email = ? WHERE username = ?"


result, err := db.Exec(query, "new_email@example.com", "john_doe")
if err != nil {
log.Fatal(err)
}


rowsAffected, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}

Deleting Data

query := "DELETE FROM users WHERE username = ?"


result, err := db.Exec(query, "john_doe")
if err != nil {
log.Fatal(err)
}


rowsAffected, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}

Using the GORM Framework

GORM is a popular Go language ORM library that supports multiple databases, including TDSQL Boundless. This guide describes how to use GORM to connect to TencentDB TDSQL Boundless and perform basic CRUD operations.

Installation Dependency

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

Connect to TDSQL Boundless

Connection String Format

dsn := "user:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"

Sample Connection Code

package main

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func main() {
dsn := "root:yourpassword@tcp(127.0.0.1:3306)/yourdb?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}

// Use the db object to perform database operations...
}

Define Model and Create Table

Define Model Struct

type User struct {
gorm.Model
Name string
Email string `gorm:"unique"`
Age int
}

Auto Migrate Create Table

// Auto Migration Mode
err = db.AutoMigrate(&User{})
if err != nil {
panic("failed to migrate database")
}

CRUD Operations Example

Create Record

// Create a single user
user := User{Name: "Zhang San", Email: "zhangsan@example.com", Age: 25}
result := db.Create(&user)
if result.Error != nil {
panic(result.Error)
}

// Batch create
users := []User{
{Name: "Li Si", Email: "lisi@example.com", Age: 30},
{Name: "Wang Wu", Email: "wangwu@example.com", Age: 28},
}
db.Create(&users)

Query record

// Query a single user
var user User
db.First(&user, 1) // Query by primary key
db.First(&user, "name = ?", "Zhang San") // Query by condition

// Query multiple users
var users []User
db.Find(&users) // Query all users
db.Where("age > ?", 25).Find(&users) // Conditional query

Update record

// Update a single field
db.Model(&user).Update("name", "Zhang San's new name")

// Update multiple fields
db.Model(&user).Updates(User{Name: "Zhang San's new name", Age: 26})

// Conditional update
db.Model(&User{}).Where("age < ?", 30).Update("age", gorm.Expr("age + ?", 1))

Deleting Records

// Delete a single record
db.Delete(&user)

// Delete conditionally
db.Where("name = ?", "Li Si").Delete(&User{})

// Soft delete (if the model includes gorm.Model)
db.Delete(&user) // only sets the deleted_at field

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan