Beego\orm use of Go programming

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

the previous MySQL operation that mentions go, but uses it to carry on the database the operation encapsulation, obviously has several big problems in the actual development iteration, first, the SQL operation and the statement is verbose and complex, secondly the work efficiency is not very high; If you use this method for database development, it is bound to be too much code redundancy , and it is easy to produce various problems during the use. So, today we'll look at how to use the Beego ORM Framework to help us with MySQL database operations.

ORM is the object-relational mapping, through the class or struct with the database table one by one correspondence, today we use simple database operation code to control the explanation, and in the code has the corresponding operation explanation:  

Import ("Fmt" _ "Github.com/go-sql-driver/mysql" "github.com/astaxie/beego/orm"//corresponding Beego/orm library can be obtained via Go Get to get to local Gopath path under "Time")//struct with Database Student table mapping type studentinfo struct {Id int ' pk: "Auto" ' Stuname string ' orm: "Si Ze "' stuidentify string ' orm:" Size (+) "' Stubirth time.  Timestuclass string ' orm: ' Size (+) ' Stumajor string ' orm: ' Size (30) '}//database The information required by the object var (dbuser string = "root" dbpwd string = "691214" dbname string = "Gosql")//Initialize ORMFUNC init () {conn: = Dbuser + ":" + dbpwd + "@/" + dbname + "? Charset=utf 8 "//Group synthetic connection string <span style=" White-space:pre "></span>orm. Registermodel (New (Studentinfo))//Registry Studentinfo If no ORM is created automatically. Registerdriver ("MySQL", Orm.) DR_MYSQL)//Register MySQL driver ORM. RegisterDatabase ("Default", "MySQL", conn)//Set the database in conn to use the database ORM by default. RUNSYNCDB ("Default", False, False)//after a use of true will bring a lot of printing information, database operations and build table operations; The second is true to force the creation of the table}func Main () {orm. Debug = True//true Print database operation log information dbobj: = orm. Neworm ()//Instantiate database operation object <span style= "White-space:pre" ></span>//Insert Data
sql: = Fmt. Sprintf ("INSERT into Studentinfo (Id,stuname, Stuidentify, Stubirth, Stuclass, stumajor)" + "values (1, ' rjx ', ' Xxx319928xxx ', '%s ', ' Faith Tube Class 1 ', ' information management and Information System '), ' 1992-01-01 11:11:11 ') fmt. PRINTLN (SQL) _, Err: = Dbobj.raw (sql). Exec () if err! = Nil {fmt. Println ("Insert data to: T_studentinfo error")} sql = Fmt. Sprintf ("INSERT into Studentinfo (Id, Stuname, Stuidentify, Stubirth, Stuclass, stumajor)" + "VALUES (2, ' qcy ', ' Xxx319918xxx ', '%s ', ' XXX ', ' yyyyyy ') ', ' 1992-01-01 11:11:11 ') _, err = Dbobj.raw (sql). Exec () if err! = Nil {fmt. Println ("Insert data to: T_studentinfo error")}//Update data sql = "Update studentinfo set stuname= ' Qcym ' where Id= 2" _, Err = Dbobj.raw (SQL). Exec () if err! = Nil {fmt. PRINTLN ("Error updating T_studentinfo table")}//Data insertion by transaction method err = Dbobj.begin () sql = FMT. Sprintf ("INSERT into Studentinfo (Id, Stuname, Stuidentify, Stubirth, Stuclass, stumajor)" + "VALUES (3, ' Loe ', ' Xxx319918xxx ', '%s ', ' zzzz ', ' tttt ') ', ' 1992-01-01 11:11:11 ') _, err = Dbobj.raw (sql). Exec () if err! = Nil {dbobj.rollback () fmt. Println ("Insert T_studeNtinfo table error, transaction rollback ")} else {dbobj.commit () fmt. Println ("Insert T_studeninfo table succeeded, transaction commit")}//Query database students: = make ([]studentinfo,]//var students []studentinfosql = "sel ECT id,stuname,stuidentify,stubirth,stuclass,stumajor from Studentinfo "FMT. PRINTLN (SQL) num, er: = Dbobj.raw (sql). QueryRows (&students) if er! = nil {fmt. PRINTLN ("Error querying Student Information")} else {fmt. Printf ("Query from T_studeninfo table to record:%d \ n", num) for index, _: = Range students {FMT. Printf ("%d Student personal information:", index+1) fmt. Printf ("Name:%s, Social Security number:%s, date of birth:%s, class:%s, Professional:%s", Students[index]. Stuname, Students[index]. Stuidentify, Students[index]. Stubirth, Students[index]. Stuclass, Students[index]. stumajor)}}//<span style= "White-space:pre" &GT;&LT;/SPAN&GT;}

Above ORM Operation basically completed to the database of additions and deletions to the operation, but the common characteristics are believed to know, is all using SQL statements to complete, then we completely use the structure to the corresponding function. This will be more convenient to operate, equivalent to the 30% framework has helped me to completely set up the DAO, database operation layer, we just need to do a simple package on this line.

The following is the use of the structure to complete the same function:

Func Main () {orm. Debug = truedbobj: = orm. Neworm () var stuptr *studentinfo = new (studentinfo) Stuptr.stuname = "Xiaom" Stuptr.stubirth = time. Now () Stuptr.stuclass = "First grade Class 1" stuptr.stuidentify = "1234" stuptr.stumajor = "Computer" TM: = time. Now () var studentus = []studentinfo{{stuname: "XD", Stuidentify: "1235", Stubirth:tm, Stuclass: "First Grade 2 Class", Stumajor: "Database"},  {stuname: "xx", Stuidentify: "1236", Stubirth:tm, Stuclass: "First Grade 3 class", Stumajor: "Network"},{stuname: "xn", stuidentify: "1237", STUBIRTH:TM, Stuclass: "First Grade 4 Class", Stumajor: "C language"},{stuname: "XB", Stuidentify: "1238", Stubirth:tm, Stuclass: "First Grade 5 class", S Tumajor: "JAVA"},{stuname: "Xq", Stuidentify: "1239", Stubirth:tm, Stuclass: "First grade Class 6", Stumajor: "C + +"},}var err Error_, E rr = Dbobj.insert (stuptr)//single record insert if err! = Nil {fmt. Printf ("Inserting student:%s Information" error.) \ n ", Stuptr.stuname)} else {fmt. Printf ("Insert student:%s information succeeded. \ n ", stuptr.stuname)}var num int64num, err = Dbobj.insertmulti (5, Studentus)//Multiple records inserted if err! = Nil {fmt. Printf ("Insert%d student information error,%d learning information succeeded.") \ n ", 5-num, num)} else {FMt. Printf ("Insert%d student information successfully.") \ n ", num)}studentr: = new (Studentinfo)//record read, need to specify primary key studentr.id = 6err = Dbobj.read (STUDENTR) if err! = Nil {fmt. Printf ("Read id:%d Student information failed", studentr.id)} else {fmt. Printf ("id:%d's student personal information is: \ n", studentr.id) fmt. Println (studentr)}studentu: = new (studentinfo) studentu.id = 5studentu.stumajor = "Management Science and Engineering" _, Err = Dbobj.update ( Studentu, "stumajor")//Record update if Err! = Nil {fmt. Printf ("Update id:%d student information failed. ", Studentu.id)} else {fmt. Printf ("Update id:%d student information is successful. ", studentu.id)}///delete dbobj.delete (Studentu)//}
Above for Beego operation MySQL database basic usage, hope to everyone has help, can achieve the same goal also have beedb, have time can refer to.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.