zoukankan      html  css  js  c++  java
  • Go 操作数据库尝鲜

    Go 操作数据库尝鲜

    以下代码为go链接mysql操作mysql的部分代码

    package main
    
    import (
    	"database/sql"
    	"fmt"
    	_ "github.com/go-sql-driver/mysql"
    )
    
    type User struct{
    	ID int64
    	Name string
    	Age int8
    }
    
    var db *sql.DB
    
    func InitDB() (err error) {
    	dbh := "bbsgo:bbsgo1234!@tcp(192.168.0.155:3306)/bbsgo_db"
    	db, err = sql.Open("mysql", dbh)
    	if err != nil {
    		return err
    	}
    	err = db.Ping()
    	if err != nil {
    		return err
    	}
    	return nil
    }
    
    func CreateTable()  {
    	sqlStr := "create table IF NOT EXISTS sqlTest1 (ID int AUTO_INCREMENT PRIMARY KEY, Name varchar(12) " +
    		"NOT NULL UNIQUE, AGE TINYINT NOT NULL)"
    	ret, err := db.Exec(sqlStr)
    	if err != nil {
    		fmt.Println(err.Error())
    		return
    	}
    	fmt.Println(ret)
    	fmt.Println(ret)
    	r, err := ret.RowsAffected()
    	fmt.Println(r)
    	fmt.Println(err)
    }
    func InsertData()  {
    	sqlStr := "insert into sqlTest(Name, AGE) value(?, ?)"
    	ret, err := db.Exec(sqlStr, "asd", 1)
    	if err != nil {
    		fmt.Println(err.Error())
    		return
    	}
    	fmt.Println(ret)
    	fmt.Println(ret)
    	r, err := ret.RowsAffected()
    	fmt.Println(r)
    	fmt.Println(err)
    }
    
    func Select() {
    	sqlStr := "SELECT * FROM sqlTest;"
    	var uList []*User
    
    	var u User
    	ret, err := db.Query(sqlStr)
    
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer ret.Close()
    	fmt.Println(ret, *ret)
    	for ret.Next() {
    		err := ret.Scan(&u.ID, &u.Name, &u.Age)
    		if err != nil {
    			fmt.Println(err)
    		} else {
    			uList = append(uList, &u)
    		}
    	}
    	fmt.Println(uList)
    	fmt.Println(uList[0])
    }
    
    func main() {
    	err := InitDB()
    	if err != nil {
    		fmt.Println(err)
    	}
    	//CreateTable()
    	//InsertData()
    	Select()
    }
    
  • 相关阅读:
    CPT104-labs
    Java-数据结构-ArrayList
    INT104-lab13[Parzen Window Method][此方法无数据集划分]
    INT104-lab12 [KNN Algorithm][lambda表达式]
    INT104-lab11 [聚类] [iris数据集] [K-means Algorithm]
    Nginx配置https兼容http
    JS获取整个网页html代码
    nginx重启生效conf文件的修改
    WampServer
    在win10系统中,开启hyper-v要满足下列条件
  • 原文地址:https://www.cnblogs.com/linga/p/14176400.html
Copyright © 2011-2022 走看看