Go數據庫操作:3、SqlMap及SqlTemplate模板

       注意: 這邊看的包是xormplus下面的包,如果是原來的xorm包,是不支持sqlMap或者template的操作的,這邊的安裝方式是:go get -u github.com/xormplus/xorm

      這邊記錄的主要還是以json方式的,所以如果需要使用其他方式,請查看原文:SqlMap及SqlTemplate模板

1、註冊sqlMap(json方式)

      

1、初始化引擎

		import (
	    _ "github.com/go-sql-driver/mysql"
	    "github.com/xormplus/xorm"
	)
	
	var engine *xorm.Engine
	
	func main() {
	    var err error
	    engine, err = xorm.NewEngine("mysql", "root:123@/test?charset=utf8")
	}

      

2、註冊json文件的sqlMap

      

	err = x.RegisterSqlMap(xorm.Json("./sql/mysql", ".json"))
	if err != nil {
		t.Fatal(err)
	}

      

3、Json文件配置

      
      配置的話其實就是key-value的形式,一個key對應一個sql這樣,後面的話,通過key的值來獲取對應的sql,比如下面這個,具體參考json模板樣式

	{
	  "json_selectAllArticle": "select id,title,createdatetime,content from Article where id in (?1,?2)",
	  "json_selectStudentById1": "select * from user where id=?id and 1=1",
	  "json_sql_2_1": "select id,title,createdatetime,content from Article where id = ?id",
	  "json_sql_i_1": "INSERT INTO categories VALUES (?id, ?name, ?counts, ?orders, ?pid)",
	  "json_sql_i_2": "INSERT INTO categories VALUES (?id, ?name, ?counts, ?orders, ?pid)",
	  "json_category": "select * from category",
	  "json_category-16-17": "select * from category where id in (16,17) and name='dd'"
	}

      

2、SqlTemplate

      
      SqlTemplate其實我也不是很明白具體的用法,後面再看吧,具體的參考上面的原文地址。

      

3、文件更新監控功能

      
      開啓SqlMap配置文件和SqlTemplate配置文件更新監控功能,將配置文件更新內容實時更新到內存,如無需要可以不調用該方法:

	//該監控模式下,如刪除配置文件,內存中不會刪除相關配置
	engine.StartFSWatcher() //開啓監控

	engine.StopFSWatcher() //停止監控

      

4、模板加密存儲及解析

      
      查看原文:SqlMap配置文件及SqlTemplate模板加密存儲及解析,這個應該用的不會很多。

      

5、手動管理

      
      這個手動管理就是在你沒有初始化的情況下有,也可以在需要的地方實現新增、更新、刪除sqlMap或者sqlTemplate的操作。

這邊只記錄sqlMap的增刪改查的方式,sqlTemplate類似不做記錄,可以直接查看原文。
      

1、新增

      


	engine.LoadSqlMap(filepath)            //加載指定文件的SqlMap配置
	
	engine.BatchLoadSqlMap([]filepath)    //批量加載指定文件的SqlMap配置
	
	engine.AddSql(key, sql)   			  //新增一條SqlMap配置

      

2、刪除

      


	engine.RemoveSql(key)			 //刪除一條SqlMap配置

	engine.BatchAddSql(map[key]sql)  //批量新增SqlMap配置
	
	engine.BatchRemoveSql([]key)     //批量刪除SqlMap配置

      

3、修改

      


	engine.ReloadSqlMap(filepath)  		   //重新加載指定文件的SqlMap配置
	
	engine.BatchReloadSqlMap([]filepath)  //批量重新加載指定文件的SqlMap配置

	engine.UpdateSql(key, sql)            //更新一條SqlMap配置

	engine.BatchUpdateSql(map[key]sql)    //批量更新SqlMap配置

      

4、查詢

      


	engine.GetSqlMap("Test_GetSqlMap_1")  //返回key爲Test_GetSqlMap_1的SqlMap配置
	
	engine.GetSqlMap("Test_GetSqlMap_1", "Test_GetSqlMap_3") //返回key爲Test_GetSqlMap_1,Test_GetSqlMap_3的SqlMap配置,如果key對應的sql不存在則返回空字符串
	
	engine.GetSqlMap([]string{"Test_GetSqlMap_1", "Test_GetSqlMap_3"}) //支持字符串數組形式參數
	
	engine.GetSqlMap([]string{"Test_GetSqlMap_1", "Test_GetSqlMap_3"},"Test_GetSqlMap_2") //支持字符串數組形式和字符串參數混用
	
	engine.GetSqlMap(key...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章