标签:安装 系列化 ola app htm fun upd 增删改 Golan
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: "845438763@qq.com",
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()
}
标签:安装 系列化 ola app htm fun upd 增删改 Golan
原文地址:https://www.cnblogs.com/cx558/p/9872278.html