golang golang各种操作数据库#mongo #file

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang golang各种操作数据库#mongo #file相关的知识,希望对你有一定的参考价值。

package main;
 
import (
    "os"
    "fmt"
    "strconv"
)
 
func main() {
 
    //打开文件,返回文件指针
    file, error := os.Open("./1.txt");
    if error != nil {
        fmt.Println(error);
    }
    fmt.Println(file);
    file.Close();
 
    //以读写方式打开文件,如果不存在,则创建
    file2, error := os.OpenFile("./2.txt", os.O_RDWR|os.O_CREATE, 0766);
    if error != nil {
        fmt.Println(error);
    }
    fmt.Println(file2);
    file2.Close();
 
    //创建文件
    //Create函数也是调用的OpenFile
    file3, error := os.Create("./3.txt");
    if error != nil {
        fmt.Println(error);
    }
    fmt.Println(file3);
    file3.Close();
 
    //读取文件内容
    file4, error := os.Open("./1.txt");
    if error != nil {
        fmt.Println(error);
    }
    //创建byte的slice用于接收文件读取数据
    buf := make([]byte, 1024);
    //循环读取
    for {
        //Read函数会改变文件当前偏移量
        len, _ := file4.Read(buf);
 
        //读取字节数为0时跳出循环
        if len == 0 {
            break;
        }
 
        fmt.Println(string(buf));
    }
    file4.Close();
 
    //读取文件内容
    file5, error := os.Open("./1.txt");
    if error != nil {
        fmt.Println(error);
    }
    buf2 := make([]byte, 1024);
    ix := 0;
    for {
        //ReadAt从指定的偏移量开始读取,不会改变文件偏移量
        len, _ := file5.ReadAt(buf2, int64(ix));
        ix = ix + len;
        if len == 0 {
            break;
        }
 
        fmt.Println(string(buf2));
    }
    file5.Close();
 
    //写入文件
    file6, error := os.Create("./4.txt");
    if error != nil {
        fmt.Println(error);
    }
    data := "我是数据\r\n";
    for i := 0; i < 10; i++ {
        //写入byte的slice数据
        file6.Write([]byte(data));
        //写入字符串
        file6.WriteString(data);
    }
    file6.Close();
 
    //写入文件
    file7, error := os.Create("./5.txt");
    if error != nil {
        fmt.Println(error);
    }
    for i := 0; i < 10; i++ {
        //按指定偏移量写入数据
        ix := i * 64;
        file7.WriteAt([]byte("我是数据"+strconv.Itoa(i)+"\r\n"), int64(ix));
    }
    file7.Close();
 
    //删除文件
    del := os.Remove("./1.txt");
    if del != nil {
        fmt.Println(del);
    }
 
    //删除指定path下的所有文件
    delDir := os.RemoveAll("./dir");
    if delDir != nil {
        fmt.Println(delDir);
    }
}
// grom 简单的用法

package main

import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Product struct {
  gorm.Model
  Code string
  Price uint
}

func main() {
  db, err := gorm.Open("sqlite3", "test.db")
  if err != nil {
    panic("failed to connect database")
  }
  defer db.Close()

  // Migrate the schema
  db.AutoMigrate(&Product{})

  // Create
  db.Create(&Product{Code: "L1212", Price: 1000})

  // Read
  var product Product
  db.First(&product, 1) // find product with id 1
  db.First(&product, "code = ?", "L1212") // find product with code l1212

  // Update - update product's price to 2000
  db.Model(&product).Update("Price", 2000)

  // Delete - delete product
  db.Delete(&product)
}
package main

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type Content struct {
	Name     string
	Download int
	Date     time.Time
}

var (
	Session, _ = mgo.Dial("localhost")
	Database   = "mgo"
	Collection = "content"
	Coll       = Session.DB(Database).C(Collection)

	content = &Content{
		Name:     "this-is-good-content",
		Download: 1,
		Date:     time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
		//Date: time.Now(),
	}
)

//Drop Database
func dropDatabase() {
	fmt.Println("Drop Database")

	//db.dropDatabase()
	err := Session.DB(Database).DropDatabase()
	if err != nil {
		panic(err)
	}
}

//Insert
func testInsert() {
	fmt.Println("Test Insert into MongoDB")
	c := bson.M{
		"name": "this-is-good-content",
		"download":    1,
		"date":        time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
	}

	/*
		db.content.insert({
			Name: "this-is-good-content",
			Download:    1,
			Date:        new Date("2016-04-07"),
			}
		)
	*/
	Coll.Insert(c)

}

//Multiple Insert
func testMultipleInsert() {
	fmt.Println("Test Multiple Insert into MongoDB")
	var contentArray []interface{}

	/*
		db.content.insert([
			{
				Name: "this-is-good-content",
				Download:    1,
				Date:        new Date("2016-04-07"),
			},
			{
				Name: "this-is-good-content",
				Download:    2,
				Date:        new Date("2016-04-07"),
			},
			{
				Name: "this-is-good-content",
				Download:    3,
				Date:        new Date("2016-04-07"),
			},
			{
				Name: "this-is-good-content",
				Download:    4,
				Date:        new Date(),
			},
			]
		)
	*/
	//contentArray = append(contentArray, &Content{
	//	Name:     "this-is-good-content",
	//	Download: 1,
	//	Date:     time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
	//})
	contentArray = append(contentArray, bson.M{
		"name":     "this-is-good-content",
		"download": 1,
		"date":     time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
	})

	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content",
		Download: 2,
		Date:     time.Date(2016, 4, 8, 0, 0, 0, 0, time.UTC),
	})

	//same date
	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content",
		Download: 3,
		Date:     time.Date(2016, 4, 8, 0, 0, 0, 0, time.UTC),
	})

	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content",
		Download: 3,
		Date:     time.Date(2016, 4, 9, 0, 0, 0, 0, time.UTC),
	})

	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content2",
		Download: 4,
		Date:     time.Now(),
	})

	Coll.Insert(contentArray...)
}

//Bulk Insert
func testBulkInsert() {
	fmt.Println("Test Bulk Insert into MongoDB")
	bulk := Coll.Bulk()

	var contentArray []interface{}
	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content",
		Download: 1,
		Date:     time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
	})

	contentArray = append(contentArray, &Content{
		Name:     "this-is-good-content",
		Download: 2,
		Date:     time.Now(),
	})

	bulk.Insert(contentArray...)
	_, err := bulk.Run()
	if err != nil {
		panic(err)
	}
}

//Update
//db.collection.update(
//   <query>,
//   <update>,
//   {
//     upsert: <boolean>,
//     multi: <boolean>,
//     writeConcern: <document>
//   }
//)
func testUpdate() {
	fmt.Println("Test Update in MongoDB")

	//db.content.update({name: "this-is-good-content"})
	selector := bson.M{"name": "this-is-good-content"}

	//Update One and Replace Doc
	//update := bson.M{"download": 3}
	//err := Coll.Update(selector, update)

	//Update One
	//update := bson.M{"$set": bson.M{"download": 3}}
	//err := Coll.Update(selector, update)

	//Update All
	update := bson.M{"$set": bson.M{"download": 3}}
	_, err := Coll.UpdateAll(selector, update)
	if err != nil {
		panic(err)
	}
}

//Upsert
//db.collection.update(
//   <query>,
//   <update>,
//   {
//     upsert: <boolean>,
//     multi: <boolean>,
//     writeConcern: <document>
//   }
//)
func testUpsert() {
	fmt.Println("Test Upsert in MongoDB")

	//Upsert
	update := bson.M{"$inc": bson.M{"download": 3}}
	selector := bson.M{"name": "this-is-good-content3"}

	_, err := Coll.Upsert(selector, update)
	if err != nil {
		panic(err)
	}
}

//Bulk Upsert
func testBulkUpsert() {
	fmt.Println("Test Bulk Upsert in MongoDB")
	bulk := Coll.Bulk()

	//Upsert
	update := bson.M{"$inc": bson.M{"download": 3}}
	selector := bson.M{"name": "this-is-good-content3"}

	bulk.Upsert(selector, update)
	bulk.Upsert(selector, update)
	bulk.Upsert(selector, update)
	_, err := bulk.Run()
	if err != nil {
		panic(err)
	}
}

//Select
func testSelect() {
	fmt.Println("Test Select in MongoDB")
	var result Content
	var results []Content
	var query bson.M
	var err error

	//query := bson.M{"download": 1}
	//Select One
	err = Coll.Find(nil).One(&result)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Select One: %+v\n", result)

	//Select Limit
	iter := Coll.Find(nil).Limit(2).Iter()
	err = iter.All(&results)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Select Limit: %+v\n", results)

	//Select All
	err = Coll.Find(nil).All(&results)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Select All: %+v\n", results)

	//Select with query
	query = bson.M{"name": "this-is-good-content"}
	err = Coll.Find(query).All(&results)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Select contentname: %+v\n", results)

	//Sort (ascending order)
	query = bson.M{"name": "this-is-good-content"}
	err = Coll.Find(query).Sort("download").All(&results)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Ascending sorted Result: %+v\n", results)

	//Sort (descending order)
	query = bson.M{"name": "this-is-good-content"}
	err = Coll.Find(query).Sort("-download").All(&results) //add - left side
	if err != nil {
		panic(err)
	}
	fmt.Printf("Descending sorted Result: %+v\n", results)
}

//Aggregate
func testAggregate() {
	pipeline := []bson.M{
		{"$match": bson.M{"name": "this-is-good-content" }},
		{"$group":
			bson.M{"_id": "$date",
			//bson.M{"_id": "$name",
				"download": bson.M{ "$sum": "$download" },
			},
		},
		{"$sort":
			bson.M{"download": 1},  //1: Ascending, -1: Descending
		},
	}
	pipe := Coll.Pipe(pipeline)

	result := []bson.M{}
	//err := pipe.AllowDiskUse().All(&result) //allow disk use
	err := pipe.All(&result)
	if err != nil {
		panic(err)
	}
	fmt.Println("result:", result)
}

func main() {
	dropDatabase()
	//testInsert()
	testMultipleInsert()
	//testBulkInsert()
	//testUpdate()
	testUpsert()
	//testBulkUpsert()
	testSelect()
	testAggregate()

}
db.col1.ensureIndex({'colors':1})   # 添加index
package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Todo struct {
	ID        bson.ObjectId `bson:"_id,omitempty"`
	Title     string
	Completed bool
}

var todosCollection *mgo.Collection
var session *mgo.Session

func init() {
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	session.SetMode(mgo.Monotonic, true)

	// get a Collection of todo
	todosCollection = session.DB("test-todo").C("todo")
}

func main() {
	defer session.Close()
	router := gin.Default()

	v1 := router.Group("/api/v1/todos")
	{
		v1.POST("/", createTodo)
		v1.GET("/", fetchAllTodo)
		v1.GET("/:id", fetchSingleTodo)
		v1.PUT("/:id", updateTodo)
		v1.DELETE("/:id", deleteTodo)
	}

	router.Run()
}

func createTodo(context *gin.Context) {
	title := context.PostForm("Title")
	completed, _ := strconv.ParseBool(context.PostForm("Completed"))
	var todo = Todo{bson.NewObjectId(), title, completed}
	fmt.Println("" + todo.Title + " completed: " + strconv.FormatBool(todo.Completed))
	err := todosCollection.Insert(&todo)
	if err != nil {
		log.Fatal(err)
	}

	context.JSON(http.StatusCreated, gin.H{
		"status":  http.StatusCreated,
		"message": "todo item created successfully",
	})
}

func fetchAllTodo(context *gin.Context) {
	var todos []Todo
	err := todosCollection.Find(nil).All(&todos)
	if err != nil {
		log.Fatal(err)
	}

	if len(todos) <= 0 {
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "no todo found",
		})
		return
	}

	context.JSON(http.StatusOK, gin.H{
		"status": http.StatusOK,
		"data":   todos,
	})
}

func fetchSingleTodo(context *gin.Context) {
	todo := Todo{}
	id := bson.ObjectIdHex(context.Param("id"))
	err := todosCollection.FindId(id).One(&todo)

	if err != nil || todo == (Todo{}) {
		fmt.Println("Error: " + err.Error())
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "todo not found",
		})
		return
	}

	context.JSON(http.StatusOK, gin.H{
		"status": http.StatusOK,
		"data":   todo,
	})
}

func updateTodo(context *gin.Context) {
	id := bson.ObjectIdHex(context.Param("id"))
	title := context.PostForm("title")
	completed, _ := strconv.ParseBool(context.PostForm("completed"))

	err := todosCollection.UpdateId(id, bson.M{"title": title, "completed": completed})

	fmt.Printf("completed: %t\n\n", completed)

	if err != nil {
		fmt.Println("Error: " + err.Error())
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "todo not found",
		})
		return
	}

	context.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "Todo updated successfully!",
	})
}

func deleteTodo(context *gin.Context) {
	id := bson.ObjectIdHex(context.Param("id"))

	fmt.Printf("id: %v", id)

	err := todosCollection.RemoveId(id)

	if err != nil {
		fmt.Println("Error: " + err.Error())
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "todo not found",
		})
		return
	}

	context.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "Todo deleted successfully!",
	})
}

golang学习----数据库操作

golang 操作数据库

golang操作数据库的过程十分简单,以下是一个简单的增删改查的操作,这里我们使用MySQL数据库为例。

连接数据库

? 连接数据库我们首先需要下载相应数据库的驱动,这里我们选择的是MySQL数据库驱动,所以我们先去拉取驱动。在这之前我们需要有git-下载地址: https://git-scm.com/ ,若下载速度慢,建议使用如下地址 https://npm.taobao.org/mirrors/git-for-windows/ 选择相应的版本下载即可。

  1. go get github.com/go-sql-driver/mysql 拉取驱动,若是其他数据库可以修改后面的名称或去相应的github上寻找

  2. import ( _ "github.com/go-sql-driver/mysql") 在代码中导入这个驱动包,这么做会调用mysql包中的init方法。

  3. var db *sql.DB
    func conn(){
    open, err := sql.Open(&quot;mysql&quot;, &quot;user:password@tcp(127.0.0.1:3306)/demo_db&quot;) // 这里的地址若是本地3306接口可以写成user:password@tcp(127.0.0.1:3306)/demo_db
    if err!=nil {   log.Fatal(err)   panic(err)} 
    db = open
    }

数据操作

插入数据

//  数据添加
func add(){  
    _, err := db.Exec("insert into user (name, age, email) value (?,?,?)", "张三", 20, "zhang@example.com")   
    if err!=nil {      
        fmt.Println(err)      
        panic(err)   
    }
}

删除数据

//  数据删除
func remove(){   
    exec, err := db.Exec("delete from user where id = ?", 6)   
    if err != nil {      
        fmt.Println(err)      
        panic(err)   
    }   
    fmt.Println(exec.RowsAffected())
}

修改数据

func modify(){
    exec, err := db.Exec("update user set name = ?,age = ? where id = ?", "babiqus", "22", 6)   
    if err!=nil {    
        fmt.Println(err)     
        panic(err)  
    }   
    fmt.Println(exec.RowsAffected())
}

查询数据

func query() {   
    query, err := db.Query("select * from user")  
    if err!=nil {    
        log.Fatal(err)    
        panic(err)  
    }  
    defer query.Close()   
    // 必须要把 query 里的内容读完,或者显式调用 Close() 方法,   
    // 否则在 defer 的 rows.Close() 执行之前,连接永远不会释放   
    var userList []User
    for query.Next(){   
        user := new(User)   
        err := query.Scan(&user.id,&user.name,&user.age,&user.email)    
        if err != nil{    
            log.Fatal(err)    
        }    
        userList = append(userList, *user)   
    }  
    for _, value := range userList {  
        fmt.Println(value)  
    }
}

使用

func init(){  
    conn()
}
func main() {   
    //add()  
    //modify()
    //remove()  
    query()
    defer db.Close()
}

以上是关于golang golang各种操作数据库#mongo #file的主要内容,如果未能解决你的问题,请参考以下文章

golang从channel读数据的各种情况

golang怎么实现psd

golang学习之旅:使用go语言操作mysql数据库

知识分享之Golang——精选的组件库、组件列表,各种golang组件都可找到

golang命令行库Cobra的使用

golang并发介绍