Go Web --- 创建一个Article的增删改查

  掌握数据的增删改查之后,就可以做一些小demo,巩固一下基础,让语法更加熟练,所以下面是按照Go web编程里面的文章管理操作,写的一个代码:

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

type Article struct {
	Id         int
	Title      string
	Content    string
	Author     string
	CreateTime string
}

var db *sql.DB  //注意db的类型,声明成全局变量是为了让所有的方法和函数都能使用
var err error

//init会在主函数之前执行
func init() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8"
	db, err = sql.Open("mysql", dsn)
	CheckError(err)
}

func CheckError(err interface{}) {
	if err != nil {
		panic(err)
	}
}

func (article *Article) AddArticle() bool {
	str := "insert into article (title,content,author,create_time) values (?,?,?,?)"
	stmt, err := db.Prepare(str)
	CheckError(err)
	result, err := stmt.Exec(article.Title, article.Content, article.Author, article.CreateTime)
	CheckError(err)
	if num, _ := result.RowsAffected(); num > 0 {
		id, _ := result.LastInsertId()
		fmt.Println("Add article", id, " success")
		return true
	} else {
		fmt.Println("Add article", article.Id, " failed")
		return false
	}
}

func (article *Article) DeleteArticle() bool {
	str := "delete from article where id=?"
	stmt, err := db.Prepare(str)
	CheckError(err)
	result, err := stmt.Exec(article.Id)
	CheckError(err)
	if num, _ := result.RowsAffected(); num > 0 {
		fmt.Println("delete article", article.Id, " success")
		return true
	} else {
		fmt.Println("delete article", article.Id, " failed")
		return false
	}
}

func GetArticleById(id int) (Article, error) {
	article := Article{Id: id}
	str := "select title,content,author,create_time from article where id=?"
	stmt, err := db.Prepare(str)
	CheckError(err)
	stmt.QueryRow(id).Scan(&article.Title, &article.Content, &article.Author, &article.CreateTime)
	return article, nil
}

func GetArticleList(start, offset int) []Article {
	var articles []Article
	str := "select id,title,content,author,create_time from article limit ?,?"
	stmt, _ := db.Prepare(str)
	rows, err := stmt.Query(start, offset)
	CheckError(err)
	for rows.Next() {
		article := Article{}
		rows.Scan(&article.Id, &article.Title, &article.Content, &article.Author, &article.CreateTime)
		articles = append(articles, article)
	}
	rows.Close()
	return articles
}

func (article *Article) UpdateArticle() bool {
	str := "update article set title=?,content=?,author=?,create_time=? where id=?"
	stmt, _ := db.Prepare(str)
	result, err := stmt.Exec(article.Title, article.Content, article.Author, article.CreateTime, article.Id)
	CheckError(err)
	if num, _ := result.RowsAffected(); num > 0 {
		return true
	} else {
		return false
	}
}

func main() {

}

  

  

posted @ 2018-07-17 19:03  寻觅beyond  阅读(320)  评论(0编辑  收藏  举报
返回顶部