github.com/gogf/gf@v1.16.9/.example/database/gdb/mssql/gdb_sqlserver.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	//_ "github.com/denisenkom/go-mssqldb"
     8  	"github.com/gogf/gf/database/gdb"
     9  	"github.com/gogf/gf/frame/g"
    10  )
    11  
    12  // 本文件用于gf框架的mssql数据库操作示例,不作为单元测试使用
    13  
    14  var db gdb.DB
    15  
    16  // 初始化配置及创建数据库
    17  func init() {
    18  	gdb.AddDefaultConfigNode(gdb.ConfigNode{
    19  		Host:    "127.0.0.1",
    20  		Port:    "1433",
    21  		User:    "sa",
    22  		Pass:    "123456",
    23  		Name:    "test",
    24  		Type:    "mssql",
    25  		Role:    "master",
    26  		Charset: "utf8",
    27  	})
    28  	db, _ = gdb.New()
    29  
    30  	//gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame")
    31  	//db = g.Database()
    32  
    33  	//gdb.SetConfig(gdb.ConfigNode {
    34  	//    Host : "127.0.0.1",
    35  	//    Port : 3306,
    36  	//    User : "root",
    37  	//    Pass : "123456",
    38  	//    Name : "test",
    39  	//    Type : "mysql",
    40  	//})
    41  	//db, _ = gdb.Instance()
    42  
    43  	//gdb.SetConfig(gdb.Config {
    44  	//    "default" : gdb.ConfigGroup {
    45  	//        gdb.ConfigNode {
    46  	//            Host     : "127.0.0.1",
    47  	//            Port     : "3306",
    48  	//            User     : "root",
    49  	//            Pass     : "123456",
    50  	//            Name     : "test",
    51  	//            Type     : "mysql",
    52  	//            Role     : "master",
    53  	//            Weight : 100,
    54  	//        },
    55  	//        gdb.ConfigNode {
    56  	//            Host     : "127.0.0.2",
    57  	//            Port     : "3306",
    58  	//            User     : "root",
    59  	//            Pass     : "123456",
    60  	//            Name     : "test",
    61  	//            Type     : "mysql",
    62  	//            Role     : "master",
    63  	//            Weight : 100,
    64  	//        },
    65  	//        gdb.ConfigNode {
    66  	//            Host     : "127.0.0.3",
    67  	//            Port     : "3306",
    68  	//            User     : "root",
    69  	//            Pass     : "123456",
    70  	//            Name     : "test",
    71  	//            Type     : "mysql",
    72  	//            Role     : "master",
    73  	//            Weight : 100,
    74  	//        },
    75  	//        gdb.ConfigNode {
    76  	//            Host     : "127.0.0.4",
    77  	//            Port     : "3306",
    78  	//            User     : "root",
    79  	//            Pass     : "123456",
    80  	//            Name     : "test",
    81  	//            Type     : "mysql",
    82  	//            Role     : "master",
    83  	//            Weight : 100,
    84  	//        },
    85  	//    },
    86  	//})
    87  	//db, _ = gdb.Instance()
    88  }
    89  
    90  // 创建测试数据库
    91  func create() error {
    92  	fmt.Println("drop table aa_user:")
    93  	_, err := db.Exec("drop table aa_user")
    94  	if err != nil {
    95  		fmt.Println("drop table aa_user error.", err)
    96  	}
    97  
    98  	s := `
    99          CREATE TABLE aa_user (
   100              id  int not null,
   101              name VARCHAR(60),
   102              age  int,
   103              addr varchar(60),
   104              PRIMARY KEY (id)
   105          )
   106      `
   107  	fmt.Println("create table aa_user:")
   108  	_, err = db.Exec(s)
   109  	if err != nil {
   110  		fmt.Println("create table error.", err)
   111  		return err
   112  	}
   113  
   114  	/*_, err = db.Exec("drop sequence id_seq")
   115  	  if err != nil {
   116  	      fmt.Println("drop sequence id_seq", err)
   117  	  }
   118  
   119  	  fmt.Println("create sequence id_seq")
   120  	  _, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10")
   121  	  if err != nil {
   122  	      fmt.Println("create sequence id_seq error.", err)
   123  	      return err
   124  	  }
   125  
   126  	  s = `
   127  	  CREATE TRIGGER id_trigger before insert on aa_user  for each row
   128  	  begin
   129  	  select id_seq.nextval into :new.id from dual;
   130  	  end;
   131  	  `
   132  	  _, err = db.Exec(s)
   133  	  if err != nil {
   134  	      fmt.Println("create trigger error.", err)
   135  	      return err
   136  	  }*/
   137  
   138  	_, err = db.Exec("drop table user_detail")
   139  	if err != nil {
   140  		fmt.Println("drop table user_detail", err)
   141  	}
   142  
   143  	s = `
   144          CREATE TABLE user_detail (
   145              id   int not null,
   146              site  VARCHAR(255),
   147              PRIMARY KEY (id)
   148          )
   149      `
   150  	fmt.Println("create table user_detail:")
   151  	_, err = db.Exec(s)
   152  	if err != nil {
   153  		fmt.Println("create table user_detail error.", err)
   154  		return err
   155  	}
   156  	fmt.Println("create table success.")
   157  	return nil
   158  }
   159  
   160  // 数据写入
   161  func insert(id int) {
   162  	fmt.Println("insert:")
   163  	r, err := db.Insert("aa_user", gdb.Map{
   164  		"id":   id,
   165  		"name": "john",
   166  		"age":  id,
   167  	})
   168  	fmt.Println(r.LastInsertId())
   169  	fmt.Println(r.RowsAffected())
   170  	if err == nil {
   171  		r, err = db.Insert("user_detail", gdb.Map{
   172  			"id":   id,
   173  			"site": "http://johng.cn",
   174  		})
   175  		if err == nil {
   176  			fmt.Printf("id: %d\n", id)
   177  		} else {
   178  			fmt.Println(err)
   179  		}
   180  
   181  	} else {
   182  		fmt.Println(err)
   183  	}
   184  	fmt.Println()
   185  }
   186  
   187  // 基本sql查询
   188  func query() {
   189  	fmt.Println("query:")
   190  	list, err := db.GetAll("select * from aa_user where 1=1")
   191  	if err == nil {
   192  		fmt.Println(list)
   193  	} else {
   194  		fmt.Println(err)
   195  	}
   196  
   197  	list, err = db.Table("aa_user").OrderBy("id").Limit(0, 5).Select()
   198  	if err == nil {
   199  		fmt.Println(list)
   200  	} else {
   201  		fmt.Println(err)
   202  	}
   203  	fmt.Println()
   204  }
   205  
   206  // replace into
   207  func replace() {
   208  	fmt.Println("replace:")
   209  	r, err := db.Save("aa_user", gdb.Map{
   210  		"id":   1,
   211  		"name": "john",
   212  	})
   213  	if err == nil {
   214  		fmt.Println(r.LastInsertId())
   215  		fmt.Println(r.RowsAffected())
   216  	} else {
   217  		fmt.Println(err)
   218  	}
   219  	fmt.Println()
   220  }
   221  
   222  // 数据保存
   223  func save() {
   224  	fmt.Println("save:")
   225  	r, err := db.Save("aa_user", gdb.Map{
   226  		"id":   1,
   227  		"name": "john",
   228  	})
   229  	if err == nil {
   230  		fmt.Println(r.LastInsertId())
   231  		fmt.Println(r.RowsAffected())
   232  	} else {
   233  		fmt.Println(err)
   234  	}
   235  	fmt.Println()
   236  }
   237  
   238  // 批量写入
   239  func batchInsert() {
   240  	fmt.Println("batchInsert:")
   241  	_, err := db.BatchInsert("aa_user", gdb.List{
   242  		{"id": 11, "name": "batchInsert_john_1", "age": 11},
   243  		{"id": 12, "name": "batchInsert_john_2", "age": 12},
   244  		{"id": 13, "name": "batchInsert_john_3", "age": 13},
   245  		{"id": 14, "name": "batchInsert_john_4", "age": 14},
   246  	}, 10)
   247  	if err != nil {
   248  		fmt.Println(err)
   249  	}
   250  	fmt.Println()
   251  }
   252  
   253  // 数据更新
   254  func update1() {
   255  	fmt.Println("update1:")
   256  	r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1)
   257  	if err == nil {
   258  		fmt.Println(r.LastInsertId())
   259  		fmt.Println(r.RowsAffected())
   260  	} else {
   261  		fmt.Println(err)
   262  	}
   263  	fmt.Println()
   264  }
   265  
   266  // 数据更新
   267  func update2() {
   268  	fmt.Println("update2:")
   269  	r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2)
   270  	if err == nil {
   271  		fmt.Println(r.LastInsertId())
   272  		fmt.Println(r.RowsAffected())
   273  	} else {
   274  		fmt.Println(err)
   275  	}
   276  	fmt.Println()
   277  }
   278  
   279  // 数据更新
   280  func update3() {
   281  	fmt.Println("update3:")
   282  	r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3)
   283  	if err == nil {
   284  		fmt.Println(r.LastInsertId())
   285  		fmt.Println(r.RowsAffected())
   286  	} else {
   287  		fmt.Println(err)
   288  	}
   289  	fmt.Println()
   290  }
   291  
   292  // 链式查询操作1
   293  func linkopSelect1() {
   294  	fmt.Println("linkopSelect1:")
   295  	r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(3, 5).Select()
   296  	if err == nil {
   297  		fmt.Println(r)
   298  	} else {
   299  		fmt.Println(err)
   300  	}
   301  	fmt.Println()
   302  }
   303  
   304  // 链式查询操作2
   305  func linkopSelect2() {
   306  	fmt.Println("linkopSelect2:")
   307  	r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One()
   308  	if err == nil {
   309  		fmt.Println(r)
   310  	} else {
   311  		fmt.Println(err)
   312  	}
   313  	fmt.Println()
   314  }
   315  
   316  // 链式查询操作3
   317  func linkopSelect3() {
   318  	fmt.Println("linkopSelect3:")
   319  	r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value()
   320  	if err == nil {
   321  		fmt.Println(r.String())
   322  	} else {
   323  		fmt.Println(err)
   324  	}
   325  	fmt.Println()
   326  }
   327  
   328  // 链式查询数量1
   329  func linkopCount1() {
   330  	fmt.Println("linkopCount1:")
   331  	r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count()
   332  	if err == nil {
   333  		fmt.Println(r)
   334  	} else {
   335  		fmt.Println(err)
   336  	}
   337  	fmt.Println()
   338  }
   339  
   340  // 错误操作
   341  func linkopUpdate1() {
   342  	fmt.Println("linkopUpdate1:")
   343  	r, err := db.Table("henghe_setting").Update()
   344  	if err == nil {
   345  		fmt.Println(r.RowsAffected())
   346  	} else {
   347  		fmt.Println("error", err)
   348  	}
   349  	fmt.Println()
   350  }
   351  
   352  // 通过Map指针方式传参方式
   353  func linkopUpdate2() {
   354  	fmt.Println("linkopUpdate2:")
   355  	r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update()
   356  	if err == nil {
   357  		fmt.Println(r.RowsAffected())
   358  	} else {
   359  		fmt.Println(err)
   360  	}
   361  	fmt.Println()
   362  }
   363  
   364  // 通过字符串方式传参
   365  func linkopUpdate3() {
   366  	fmt.Println("linkopUpdate3:")
   367  	r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update()
   368  	if err == nil {
   369  		fmt.Println(r.RowsAffected())
   370  	} else {
   371  		fmt.Println(err)
   372  	}
   373  	fmt.Println()
   374  }
   375  
   376  // Where条件使用Map
   377  func linkopUpdate4() {
   378  	fmt.Println("linkopUpdate4:")
   379  	r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update()
   380  	if err == nil {
   381  		fmt.Println(r.RowsAffected())
   382  	} else {
   383  		fmt.Println(err)
   384  	}
   385  	fmt.Println()
   386  }
   387  
   388  // 链式批量写入
   389  func linkopBatchInsert1() {
   390  	fmt.Println("linkopBatchInsert1:")
   391  	r, err := db.Table("aa_user").Filter().Data(gdb.List{
   392  		{"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"},
   393  		{"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"},
   394  		{"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"},
   395  		{"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"},
   396  	}).Insert()
   397  	if err == nil {
   398  		fmt.Println(r.RowsAffected())
   399  	} else {
   400  		fmt.Println(err)
   401  	}
   402  	fmt.Println()
   403  }
   404  
   405  // 链式批量写入,指定每批次写入的条数
   406  func linkopBatchInsert2() {
   407  	fmt.Println("linkopBatchInsert2:")
   408  	r, err := db.Table("aa_user").Data(gdb.List{
   409  		{"id": 25, "name": "linkopBatchInsert2john_1"},
   410  		{"id": 26, "name": "linkopBatchInsert2john_2"},
   411  		{"id": 27, "name": "linkopBatchInsert2john_3"},
   412  		{"id": 28, "name": "linkopBatchInsert2john_4"},
   413  	}).Batch(2).Insert()
   414  	if err == nil {
   415  		fmt.Println(r.RowsAffected())
   416  	} else {
   417  		fmt.Println(err)
   418  	}
   419  	fmt.Println()
   420  }
   421  
   422  // 链式批量保存
   423  func linkopBatchSave() {
   424  	fmt.Println("linkopBatchSave:")
   425  	r, err := db.Table("aa_user").Data(gdb.List{
   426  		{"id": 1, "name": "john_1"},
   427  		{"id": 2, "name": "john_2"},
   428  		{"id": 3, "name": "john_3"},
   429  		{"id": 4, "name": "john_4"},
   430  	}).Save()
   431  	if err == nil {
   432  		fmt.Println(r.RowsAffected())
   433  	} else {
   434  		fmt.Println(err)
   435  	}
   436  	fmt.Println()
   437  }
   438  
   439  // 事务操作示例1
   440  func transaction1() {
   441  	fmt.Println("transaction1:")
   442  	if tx, err := db.Begin(); err == nil {
   443  		r, err := tx.Insert("aa_user", gdb.Map{
   444  			"id":   30,
   445  			"name": "transaction1",
   446  		})
   447  		tx.Rollback()
   448  		fmt.Println(r, err)
   449  	}
   450  	fmt.Println()
   451  }
   452  
   453  // 事务操作示例2
   454  func transaction2() {
   455  	fmt.Println("transaction2:")
   456  	if tx, err := db.Begin(); err == nil {
   457  		r, err := tx.Table("user_detail").Data(gdb.Map{"id": 6, "site": "www.baidu.com哈哈哈*?''\"~!@#$%^&*()"}).Insert()
   458  		tx.Commit()
   459  		fmt.Println(r, err)
   460  	}
   461  	fmt.Println()
   462  }
   463  
   464  // 主从io复用测试,在mysql中使用 show full processlist 查看链接信息
   465  func keepPing() {
   466  	fmt.Println("keepPing:")
   467  	for i := 0; i < 30; i++ {
   468  		fmt.Println("ping...", i)
   469  		err := db.PingMaster()
   470  		if err != nil {
   471  			fmt.Println(err)
   472  			return
   473  		}
   474  		err = db.PingSlave()
   475  		if err != nil {
   476  			fmt.Println(err)
   477  			return
   478  		}
   479  		time.Sleep(1 * time.Second)
   480  	}
   481  }
   482  
   483  // like语句查询
   484  func likeQuery() {
   485  	fmt.Println("likeQuery:")
   486  	if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil {
   487  		fmt.Println(r)
   488  	} else {
   489  		fmt.Println(err)
   490  	}
   491  }
   492  
   493  // mapToStruct
   494  func mapToStruct() {
   495  	type User struct {
   496  		Id   int
   497  		Name string
   498  		Age  int
   499  		Addr string
   500  	}
   501  	fmt.Println("mapToStruct:")
   502  	if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil {
   503  		u := User{}
   504  		if err := r.ToStruct(&u); err == nil {
   505  			fmt.Println(r)
   506  			fmt.Println(u)
   507  		} else {
   508  			fmt.Println(err)
   509  		}
   510  	} else {
   511  		fmt.Println(err)
   512  	}
   513  }
   514  
   515  func main() {
   516  
   517  	db.PingMaster()
   518  	db.SetDebug(true)
   519  	/*err := create()
   520  	  if err != nil {
   521  	      return
   522  	  }*/
   523  
   524  	//test1
   525  	/*for i := 1; i < 5; i++ {
   526  	    insert(i)
   527  	}*/
   528  	//insert(2)
   529  	//query()
   530  
   531  	//batchInsert()
   532  	//query()
   533  
   534  	//replace()
   535  	//save()
   536  
   537  	/*update1()
   538  	  update2()
   539  	  update3()
   540  	*/
   541  
   542  	/*linkopSelect1()
   543  	  linkopSelect2()
   544  	  linkopSelect3()
   545  	  linkopCount1()
   546  	*/
   547  
   548  	/*linkopUpdate1()
   549  	  linkopUpdate2()
   550  	  linkopUpdate3()
   551  	  linkopUpdate4()
   552  	*/
   553  
   554  	linkopBatchInsert1()
   555  	query()
   556  	//linkopBatchInsert2()
   557  
   558  	//transaction1()
   559  	//transaction2()
   560  	//
   561  	//keepPing()
   562  	//likeQuery()
   563  	//mapToStruct()
   564  	//getQueriedSqls()
   565  }