How do you read data table structure in Golang?

In Golang, you can use the database/sql package to read a table’s structure. Below is an example code showing how to read the column names and types of a table.

package main

import (
	"database/sql"
	"fmt"

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

func main() {
	// 连接到数据库
	db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	// 查询数据表结构
	rows, err := db.Query("SHOW COLUMNS FROM table_name")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()

	// 读取每一列的名称和类型
	for rows.Next() {
		var field, typ string
		err := rows.Scan(&field, &typ)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Printf("Field: %s, Type: %s\n", field, typ)
	}

	if err = rows.Err(); err != nil {
		fmt.Println(err)
		return
	}
}

In the code above, you need to replace user:password@tcp(localhost:3306)/database with your database connection information. Replace table_name with the name of the table you want to read data from.

This code uses MySQL as an example database, you can replace “mysql” with the name of another database driver and modify the connection string accordingly based on your needs.

bannerAds