gin访问和使用数据库


package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func main() {
	// 链接数据库
	//dsn := "username:password@protocal(host:port)/dbname"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalln(err.Error())
	}

	// 创建数据表
	// person: id, name, age
	/*
		_, err = db.Exec("create table person(" +
				"id int auto_increment primary key," +
				"name varchar(12) not null," +
				"age int default 1" +
			");")
		if err != nil {
			log.Fatalln(err.Error())
		}
	*/

	// 插入数据到数据库
	/*
		_, err = db.Exec("insert into person(name, age) values(?, ?),(?, ?);", "davie", 99, "dave2", 100)
		if err != nil {
			log.Fatalln(err.Error())
		} else {
			fmt.Println("数据插入成功。")
		}
	*/

	// 查询数据库
	rows, err := db.Query("select * from person;")
	if err != nil {
		log.Fatalln(err.Error())
	}

scan:
	if rows.Next() {
		var person Person
		if err := rows.Scan(&person.Id, &person.Name, &person.Age); err != nil {
			log.Fatalln(err.Error())
		}
		fmt.Println(person)
		goto scan
	}

}
type Person struct {
	Id int
	Name string
	Age int
}

gin