zoukankan      html  css  js  c++  java
  • (三)go-sql-driver

    1. go-sql-driver/mysql

    2. CRUD 示例

    // mysql_demo project main.go
    package main
    
    import (
    	"database/sql"
    	"fmt"
    
    	_ "github.com/go-sql-driver/mysql"
    )
    
    func MysqlTest() {
    	db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/ld")
    	if err != nil {
    		fmt.Println("connect to mysql failed!")
    		return
    	} else {
    		fmt.Println("connected")
    	}
    	defer db.Close()
    
    	err = db.Ping()
    	if err != nil {
    		panic(err.Error())
    	}
    
    	// select
    	sqlSelect := "select * from ld.pet"
    	statement, err := db.Prepare(sqlSelect)
    	if err != nil {
    		fmt.Println("prepare statement failed:", err.Error())
    		return
    	}
    	defer statement.Close()
    	rows, err := statement.Query()
    	if err != nil {
    		fmt.Println("query failed:", err.Error())
    	}
    	columns, err := rows.Columns()
    	if err != nil {
    		fmt.Println(err.Error())
    		return
    	}
    	fmt.Println(columns)
    
    	row := make([]sql.RawBytes, len(columns))
    	scanArgs := make([]interface{}, len(row))
    	for i := range row {
    		scanArgs[i] = &row[i]
    	}
    
    	for rows.Next() {
    		err := rows.Scan(scanArgs...)
    		if err != nil {
    			panic(err.Error())
    		}
    		// row
    		for pos, col := range row {
    			fmt.Println(columns[pos], ":", string(col))
    		}
    		fmt.Println()
    	}
    
    	// insert
    	sqlInsert := "insert into ld.pet values('kk', 'ld', "2018-12-13", "2018-12-13 15:56:50", "2018-12-13 15:57:00")"
    	statement_insert, err := db.Prepare(sqlInsert)
    	if err != nil {
    		panic(err.Error())
    	}
    	statement_insert.Exec()
    	statement_insert.Close()
    
    	// delete
    	sqlDelete := "delete from ld.pet where name = 'kk'"
    	statement_delete, err := db.Prepare(sqlDelete)
    	if err != nil {
    		panic(err.Error())
    	}
    	statement_delete.Exec()
    	statement_delete.Close()
    
    	// update
    	sqlUpdate := "update ld.pet set ower = 'caicai' where name = 'gg'"
    	statement_update, err := db.Prepare(sqlUpdate)
    	if err != nil {
    		panic(err.Error())
    	}
    	statement_update.Exec()
    	statement_update.Close()
    
    }
    
    func main() {
    	fmt.Println("Hello World!")
    	MysqlTest()
    }
    
    
  • 相关阅读:
    [leetcode] Valid Sudoku
    [leetcode] Count and Say
    [leetcode] Decode Ways
    [leetcode] Sqrt(x)
    [leetcode] Best Time to Buy and Sell Stock II
    7-27 兔子繁衍问题
    7-26 最大公约数和最小公倍数
    7-25 求奇数和
    7-24 猜数字游戏
    7-23 分段计算居民水费
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/10114960.html
Copyright © 2011-2022 走看看