1. 程式人生 > 其它 >go語言之操作資料庫

go語言之操作資料庫

1.操作mysql資料庫

  • demo.go
package main

import (
	"database/sql"
	"fmt"

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

var student struct {
	id         int
	name       string
	province   string
	city       string
	addr       string
	score      int
	enrollment string
}

func CheckError(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func query(db *sql.DB) {
	rows, err := db.Query("select name,city,score,enrollment from student;")
	CheckError(err)
	for rows.Next() {
		err := rows.Scan(&student.name, &student.city, &student.score, &student.enrollment)
		CheckError(err)
		fmt.Println(student.name, student.city, student.score, student.enrollment)
	}
}

func insert(db *sql.DB) {
	sql := "insert into student(name,province,city,enrollment) values(?,?,?,?),(?,?,?,?)"
	res, err := db.Exec(sql, "寧靜", "貴州", "貴陽", "2021-08-13", "黃曉明", "山東", "青島", "2021-08-14")
	CheckError(err)
	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func update(db *sql.DB) {
	sql := "update student set name=? where id=?"
	res, err := db.Exec(sql, "楊戩", 4)
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func delete(db *sql.DB) {
	sql := "delete from student where city=?"
	res, err := db.Exec(sql, "成都")
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func replace(db *sql.DB) {
	// replace 跟 insert 類似, 有則修改,沒有則建立記錄
	sql := "replace into student(name,province,city,enrollment) values('紅紅', '山西', '太原', '2021-05-12')"
	res, err := db.Exec(sql)
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func write(db *sql.DB, sql string) {
	res, err := db.Exec(sql)
	CheckError(err)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func main() {
	dns := "root:passwd@2021@tcp(172.30.1.128:3306)/day12?charset=utf8"
	db, err := sql.Open("mysql", dns)
	CheckError(err)

	// insert(db)
	// delete(db)
	// update(db)
	// query(db)
	// replace(db)
	sql := "insert into student(name,province,city,enrollment) values('李世民', '陝西', '西安', '2021-05-20')"
	write(db, sql)
}

本文來自部落格園,作者:zhanghuiyan,轉載請註明原文連結:https://www.cnblogs.com/zhanghuiyan/p/15175243.html