1:sql脚本
create table post( id serial primary key, content text, author varchar(100) )
2:post.go
package post import( "fmt" "database/sql" _"github.com/lib/pq" ) const( host = "192.168.72.128" port = 5432 user = "test" password = "test" dbname = "testdb" ) type Post struct{ ID int Content string Author string } var Db *sql.DB func init(){ var err error psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "password=%s dbname=%s sslmode=disable",host, port, user, password, dbname) Db, err = sql.Open("postgres", psqlInfo) if err != nil{ panic(err) } } func (post *Post) GetPosts(limit int) (posts []Post, err error){ sql := "select id,content,author from post limit $1"; rows, err := Db.Query(sql, limit) if err != nil{ return } defer rows.Close() for rows.Next(){ post := Post{} err = rows.Scan(&post.ID, &post.Content, &post.Author) if err != nil{ return } posts = append(posts, post) } return } func (p *Post) GetPost(id int) (post Post, err error){ post = Post{} sql := "select id,content,author from post where id=$1" err = Db.QueryRow(sql, id).Scan(&post.ID, &post.Content, &post.Author) return } func (post *Post) AddPost() (err error){ sql := "insert into post(content,author) values($1,$2) returning id" stmt, err := Db.Prepare(sql) if err != nil{ return } defer stmt.Close() err = stmt.QueryRow(post.Content, post.Author).Scan(&post.ID) return } func (post *Post) DelPost()(err error){ sql := "delete from post where id=$1" _,err = Db.Exec(sql, post.ID) return } func (post *Post) EditPost() (err error){ sql := "update post set content=$1 where id=$2" _,err = Db.Exec(sql, post.Content, post.ID) return }
3:main.go
package main import( "fmt" "Chapter02/post" ) func main(){ p := post.Post{ Content: "Hello java!", Author: "王五", } fmt.Println(p) err := p.AddPost() if err != nil{ panic(err) } fmt.Println(p) var posts = []post.Post{} posts, err = p.GetPosts(10) if err != nil{ panic(err) } for _,post := range posts{ fmt.Printf("ID:%d,Content:%s,Author:%s ", post.ID, post.Content, post.Author) } pp, err := p.GetPost(p.ID) if err != nil{ panic(err) } fmt.Println(pp) }