Golang - Mysql ang Http Basic fucntions

今天总结了一些Golang的基本用法,作为记录在此!

package main

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	_ "mysql-master/mysql-master"
	"net/http"
	"strings"
)

func httpGet(url string) {

	resp, err := http.Get(url)
	if err != nil {
		// handle error
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}

	fmt.Println(string(body))
}

func httpPost(url string) {

	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader("name=cjb"))
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}

	fmt.Println(string(body))
}

func getConn() *sql.DB {
	//db, err := sql.Open("mysql", "root:1234@tcp(localhost:3306)/psmdb")
	db, err := sql.Open("mysql", "root:1234@tcp(localhost:3306)/psmdb")

	if err != nil {
		//log.Println(err)
	}

	err = db.Ping()

	if err != nil {
		log.Fatal(err)
	}

	println("connection mysql success.")

	return db
}

func query(db *sql.DB) {

	rows, err := db.Query("select id, username from psm_user where username = ?", "changeit")
	if err != nil {
		log.Println(err)
	}

	defer rows.Close()

	var id int
	var name string
	for rows.Next() {
		err := rows.Scan(&id, &name)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("id:", id, ",name:", name)
	}

	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("query success")
}

func insert(db *sql.DB) {

	stmt, err := db.Prepare("INSERT INTO psm_user(username, password) VALUES(?, ?)")

	defer stmt.Close()

	if err != nil {
		log.Println(err)
	}

	stmt.Exec("changeit", "1234")
	fmt.Println("insert success")
}

func delete(db *sql.DB) {

	tx, _ := db.Begin()

	stmt, err := db.Prepare("DELETE FROM psm_user WHERE username=?")
	stmt.Exec("changeit")

	defer stmt.Close()

	if err != nil {
		// hand err
		tx.Rollback()
		fmt.Println("delete error")
	}

	tx.Commit()
	fmt.Println("delete success")
}

func update(db *sql.DB) {

	tx, _ := db.Begin()

	stmt, err := db.Prepare("update psm_user set username = ? , password = ?")
	stmt.Exec("changeit")
	stmt.Exec("1234")

	defer stmt.Close()

	if err != nil {
		// hand err
		tx.Rollback()
		fmt.Println("update error")
	}

	tx.Commit()
	fmt.Println("update success")
}

func main() {

	httpGet("http://localhost:8088/SpringDemo/home/users/1")

	httpPost("http://localhost:8088/SpringDemo/home/user")

	db := getConn()

	insert(db)

	query(db)

	update(db)

	delete(db)
}
结果输出:

[ `go run main.go` | done: 5.25s ]
	{"id":1,"username":"admin","password":"1234"}
	{"id":2,"username":"hpe4test","password":"1234"}
	insert success
	id: 7 ,name: changeit
	query success
	update success
	delete success
	
	connection mysql success.
[ C:/MyGo/src/ ] # 

注:

驱动下载地址:https://github.com/go-sql-driver/mysql/

下载方式: 执行命令:go get github.com/go-sql-driver/mysql



你可能感兴趣的:(云计算,Golang)