1. 程式人生 > >Golang 基礎

Golang 基礎

base make 增刪改查操作 系列 Golan pkg ted 讀寫 fsd

1.go序列化,2.go讀寫文件,追加到文本方式,3.go的mysql增刪改查操作

1.go系列化(引入encoding/json包)

package main
import (
"fmt"
"encoding/json"
)
type User struct {
NickName string `json:"nickname"`
Age int
Birthday string
Sex string
Email string
Phone string
}
func main() {
user1 := &User{
NickName: "上課看似",
Age: 28,
Birthday: "1990/12/12",
Sex: "男",
Email: "[email protected]",
Phone: "13798491455",
}
data, err := json.Marshal

(user1)
if err != nil {
fmt.Printf("json.marshal failed, err:", err)
return
}
fmt.Println(string(data))

}

----------------------------------------end----------------------------------------------------

2.go讀寫文件,追加方式(引入io/ioutil,os 包)

ioutil.ReadFile讀文件方法,

package main
import(
"io/ioutil"
"fmt"
"os"
)
func main(){
read, err := ioutil.ReadFile

("log.txt")
if err != nil{
fmt.Print(err)
}

str :=string(read)
fmt.Println(str)

data := " hello haha\n\r";
appendToFile("log.txt",data)
}


func appendToFile(fileName string, content string) error {
// 以只寫的模式,打開文件
f, err := os.OpenFile(fileName, os.O_WRONLY, 0644)
if err != nil {
fmt.Println("cacheFileList.yml file create failed. err: " + err.Error())
} else {
// 查找文件末尾的偏移量
n, _ := f.Seek
(0, os.SEEK_END)
// 從末尾的偏移量開始寫入內容
_, err = f.WriteAt([]byte(content), n)
}
defer f.Close()
return err
}

---------------------------------------------------End---------------------------------------------------------------------

3.go的mysql操作

要安裝mysql 包 go get github.com/go-sql-driver/mysql (成功執行pkg和src生成包文件)

技術分享圖片

失敗,確定GO環境配置成功,( https://www.cnblogs.com/wangqishu/p/5147108.html

package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
//"strconv"
//"encoding/json"
)
type Users struct{
id int
uid int
token string

}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/shoxot?charset=utf8")
checkErr(err)

//插入數據
stmt,err:= db.Prepare("INSERT ot_token SET uid=?,token=?")
checkErr(err)
res, err := stmt.Exec(1008,"12312sfsdasd")
checkErr(err)

//獲取永遠id
id, err:=res.LastInsertId()
checkErr(err)
fmt.Println(id)


//修改數據
stmt, err = db.Prepare("UPDATE ot_token set uid=?,token=? where id=?")
res, err = stmt.Exec(1055,"sss1111",108)
affect, err := res.RowsAffected()
fmt.Println(affect)


//查詢數據

var users []Users = make([]Users,0)
rows, err :=db.Query("select * from ot_token limit 10")
for rows.Next() {
var u Users
rows.Scan(&u.id,&u.uid,&u.token)
users = append(users,u)
}
//data, err := json.Marshal(users)
fmt.Println(users)
defer db.Close()


}

Golang 基礎