更多Go内容请见: https://blog.csdn.net/weixin_39777626/article/details/85066750
Web应用存储数据的方法:
- 在程序运行时,将数据存储到内存里面
- 将数据存储到文件系统的文件里面
- 通过服务器程序前端,将数据存储到数据库里
内存存储
将数据存储到运行中的应用中,并在应用运行过程中使用这些数据
常见手段
- 数组
- 切片
- 映射
- 结构
在内存中存储数据
package main
import (
"fmt"
)
type Post struct {
Id int
Content string
Author string
}
var PostById map[int]*Post
var PostsByAuthor map[string][]*Post
func store(post Post) {
PostById[post.Id] = &post
PostsByAuthor[post.Author] = append(PostsByAuthor[post.Author], &post)
}
func main() {
PostById = make(map[int]*Post)
PostsByAuthor = make(map[string][]*Post)
post1 := Post{Id: 1, Content: "Hello World!", Author: "Sau Sheng"}
post2 := Post{Id: 2, Content: "Bonjour Monde!", Author: "Pierre"}
post3 := Post{Id: 3, Content: "Hola Mundo!", Author: "Pedro"}
post4 := Post{Id: 4, Content: "Greetings Earthings!", Author: "Sau Sheong"}
store(post1)
store(post2)
store(post3)
store(post4)
fmt.Println(PostById[1])
fmt.Println(PostById[2])
for _, post := range PostsByAuthor["Sau Sheong"] {
fmt.Println(post)
}
for _, post := range PostsByAuthor["Pedero"] {
fmt.Println(post)
}
}
文件存储
对文件进行读写
- ioutil包(更简单)
- File结构(更灵活)
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
data := []byte("Hello World!\n")
err := ioutil.WriteFile("data1", data, 0644)
if err != nil {
panic(err)
}
read1, _ := ioutil.ReadFile("data1")
fmt.Print(string(read1))
file1, _ := os.Create("data2")
defer file1.Close()
bytes, _ := file1.Write(data)
fmt.Printf("Write %d bytes to file\n", bytes)
file2, _ := os.Open("data2")
defer file2.Close()
read2 := make([]byte, len(data))
bytes, _ = file2.Read(read2)
fmt.Printf("Read %d bytes from file\n", bytes)
fmt.Println(string(read2))
}
读写CSV文件
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
)
type Post struct {
Id int
Content string
Author string
}
func main() {
csvFile, err := os.Create("posts.csv")
if err != nil {
panic(err)
}
defer csvFile.Close()
allPosts := []Post{
Post{Id: 1, Content: "Hello World!", Author: "Sau Sheong"},
Post{Id: 2, Content: "Bonjour Monde1", Author: "Pierre"},
Post{Id: 3, Content: "Hola Mundo!", Author: "Pedro"},
Post{Id: 4, Content: "Greetings Earthlings!", Author: "Sau Sheong"},
}
writer := csv.NewWriter(csvFile)
for _, post := range allPosts {
line := []string{strconv.Itoa(post.Id), post.Content, post.Author}
err := writer.Write(line)
if err != nil {
panic(err)
}
}
writer.Flush()
file, err := os.Open("posts.csv")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = -1
record, err := reader.ReadAll()
if err != nil {
panic(err)
}
var posts []Post
for _, item := range record {
id, _ := strconv.ParseInt(item[0], 0, 0)
post := Post{Id: int(id), Content: item[1], Author: item[2]}
posts = append(posts, post)
}
fmt.Println(posts[0].Id)
fmt.Println(posts[0].Content)
fmt.Println(posts[0].Author)
}
gob包(读写二进制文件)
package main
import (
"bytes"
"encoding/gob"
"fmt"
"io/ioutil"
)
type Post struct {
Id int
Content string
Author string
}
func store(data interface{}, filename string) {
buffer := new(bytes.Buffer)
encoder := gob.NewEncoder(buffer)
err := encoder.Encode(data)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(filename, buffer.Bytes(), 0600)
if err != nil {
panic(err)
}
}
func load(data interface{}, filename string) {
raw, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
buffer := bytes.NewBuffer(raw)
dec := gob.NewDecoder(buffer)
err = dec.Decode(data)
if err != nil {
panic(err)
}
}
func main() {
post := Post{Id: 1, Content: "Hello World!", Author: "Sau Sheong"}
store(post, "post1")
var postRead Post
load(&postRead, "post1")
fmt.Println(postRead)
}
Go与SQL
postgres shell的使用:
注意:使用SQL语句前需用先登录
- 红色框框部分只需根据 [ ] 里的提示填即可
- 绿色框框里的 用户postgres的口令 指 密码
#创建数据库
CREATE DATABASE testdb;
#创建数据表
CREATE TABLE posts(
id serial primary key,
content text,
author varchar(255)
);
安装Postgres驱动
cd F:\Go\goProject\src\github.com
F:
go get -u github.com/lib/pq
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type Post struct {
Id int
Content string
Author string
}
var Db *sql.DB
func init() {
var err error
Db, err = sql.Open("postgres", "user=postgres dbname=testdb password=********** sslmode=disable")
if err != nil {
panic(err)
}
}
func Posts(limit int) (posts []Post, err error) {
rows, err := Db.Query("select id,content,author from posts limit $1", limit)
if err != nil {
return
}
for rows.Next() {
post := Post{}
err = rows.Scan(&post.Id, &post.Content, &post.Author)
if err != nil {
return
}
posts = append(posts, post)
}
rows.Close()
return
}
func GetPost(id int) (post Post, err error) {
post = Post{}
err = Db.QueryRow("select id,content,author from posts where id=$1", id).Scan(&post.Id, &post.Content, &post.Author)
return
}
func (post *Post) Create() (err error) {
statement := "insert into posts (content,author) values ($1,$2) returning id"
stmt, err := Db.Prepare(statement)
if err != nil {
return
}
defer stmt.Close()
err = stmt.QueryRow(post.Content, post.Author).Scan(&post.Id)
return
}
func (post *Post) Update() (err error) {
_, err = Db.Exec("update posts set content=$2,author=$3 where id=$1", post.Id, post.Content, post.Author)
return
}
func (post *Post) Delete() (err error) {
_, err = Db.Exec("delete from posts where id=$1", post.Id)
return
}
func main() {
post := Post{Content: "Hello World!", Author: "Sau Sheong"}
fmt.Println(post)
post.Create()
fmt.Println(post)
readPost, _ := GetPost(post.Id)
fmt.Println(readPost)
readPost.Content = "Bonjour Monde!"
readPost.Author = "Pierre"
readPost.Update()
posts, _ := Posts(10)
fmt.Println(posts)
readPost.Delete()
}
Go与SQL的关系
关系型数据库——表与表之间建立联系
- 一对一关联
- 一对多关联
- 多对一关联
- 多对多关联
一对多关系
Go语言实现(一对多&多对一)
package main
import (
"database/sql"
"errors"
"fmt"
_ "github.com/lib/pq"
)
type Post struct {
Id int
Content string
Author string
Comments []Comment
}
type Comment struct {
Id int
Content string
Author string
Post *Post
}
var Db *sql.DB
func init() {
var err error
Db, err = sql.Open("postgres", "user=postgres dbname=testdb password=********** sslmode=disable")
if err != nil {
panic(err)
}
}
func (comment *Comment) Create() (err error) {
if comment.Post == nil {
err = errors.New("Post not Found")
return
}
err = Db.QueryRow("insert into comments (content,author,post_id) values ($1,$2,$3) returning id", comment.Content, comment.Author, comment.Post.Id).Scan(&comment.Id)
return
}
func GetPost(id int) (post Post, err error) {
post = Post{}
post.Comments = []Comment{}
err = Db.QueryRow("select id,content,author from posts where id=$1", id).Scan(&post.Id, &post.Content, &post.Author)
rows, err := Db.Query("select id,content,author from comments")
if err != nil {
return
}
for rows.Next() {
comment := Comment{Post: &post}
err = rows.Scan(&comment.Id, &comment.Content, &comment.Author)
if err != nil {
return
}
post.Comments = append(post.Comments, comment)
}
rows.Close()
return
}
func (post *Post) Create() (err error) {
err = Db.QueryRow("insert into posts (content,author) values ($1,$2) returning id", post.Content, post.Author).Scan(&post.Id)
return
}
func main() {
post := Post{Content: "Hello World!", Author: "Sau Sheong"}
post.Create()
comment := Comment{Content: "Good post!", Author: "Joe", Post: &post}
comment.Create()
readPost, _ := GetPost(post.Id)
fmt.Println(readPost)
fmt.Println(readPost.Comments)
fmt.Println(readPost.Comments[0].Post)
}
Go与关系映射器
关系映射器:把关系数据库中的表映射为编程语言中的对象
Sqlx
package main
import (
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
type Post struct {
Id int
Content string
AuthorName string `db:author`
}
var Db *sqlx.DB
func init() {
var err error
Db, err = sqlx.Open("postgres", "user=postgres dbname=testdb password=******** sslmode=disable")
if err != nil {
panic(err)
}
}
func GetPost(id int) (post Post, err error) {
post = Post{}
err = Db.QueryRowx("select id,content,author from posts where id=$1", id).StructScan(&post)
if err != nil {
return
}
return
}
func (post *Post) Create() (err error) {
err = Db.QueryRow("insert into posts (content,author) values ($1,$2) returning id", post.Content, post.AuthorName).Scan(&post.Id)
return
}
func main() {
post := Post{Content: "Hello World!", AuthorName: "Sau Sheong"}
post.Create()
fmt.Println(post)
}
Gorm
package main
import (
"fmt"
"time"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type Post struct {
Id int
Content string
Author string `sql:"not null"`
Comments []Comment
CreateAt time.Time
}
type Comment struct {
Id int
Content string
Author string `sql:"not null"`
PostId int `sql:"index"`
CreatedAt time.Time
}
var Db *gorm.DB
func init() {
var err error
Db, err = gorm.Open("postgres", "user=postgres dbname=testdb password=3141596 sslmode=disable")
if err != nil {
panic(err)
}
Db.AutoMigrate(&Post{}, &Comment{})
}
func main() {
post := Post{Content: "Hello World!", Author: "Sau Sheong"}
fmt.Println(post)
Db.Create(&post)
fmt.Println(post)
comment := Comment{Content: "Good post!", Author: "Joe"}
Db.Model(&post).Association("Comments").Append(comment)
var readPost Post
Db.Where("author=$1", "Sau Sheong").First(&readPost)
var comments []Comment
Db.Model(&readPost).Related(&comments)
fmt.Println(comments[0])
}
更多Go内容请见: https://blog.csdn.net/weixin_39777626/article/details/85066750