Self-encapsulated Golang operation database method

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. This is the first thing I wrote with Go, there may be some bugs that haven't been tested. Here is mainly to provide a reference. You can rewrite your style.

Enter the following two commands at the command line to install

Go get github.com/male110/simpledb        go install github.com/male110/simpledb

The Go Language database operation, can only use Rows.scan to read all the columns at once. Feeling very unaccustomed, I still used to follow the column name to a column of data fetching. So I encapsulated a data structure myself. Myrows,myrows implements a function that GetValue (name string, value interface{}) can fetch by column name. As shown below:

Err = rows. GetValue ("Isboy", &isboy)        if err! = Nil {            FMT. PRINTLN (Err)            return        }

For ease of operation, other structures are defined, such as mydb, whose query function can be returned directly to Myrows. NEWDB is used to create the MYDB structure with its arguments with SQL. Open one to, how to pass depends on the driver that you use.

 db, err: = simpledb.newdb ("MySQL", "root:123@tcp (127.0.0.1:3306)/test?charset=utf8") if err! = Nil {fmt. PRINTLN ("Error opening sql:", err.) Error ()) return} var rows *simpledb.myrows//Fetch data from the database rows, err = db. Query ("SELECT * FROM person") if err! = Nil {fmt. PRINTLN (ERR) return}//displays data for rows. Next () {var id, age int var name string var isboy bool//Fetch data by field name, or rows. Scan (&id,&name,&age) to fetch rows. GetValue ("id", &id) rows. GetValue ("name", &name) rows. GetValue ("Age", &age)//can determine if the success of err = rows is based on the return value. GetValue ("Isboy", &isboy) if err! = Nil {fmt. PRINTLN (ERR) return} FMT. Println (ID, "\ t", name, "\ T", age, "\ T", Isboy)} 

At the same time, a simple ORM is implemented, which realizes the most basic inserting data, modifies the data and deletes the data. I generally use ORM in only a few ways, the other is to write SQL statements. Here is only a reference, we can according to their own needs, their own habits, to make changes. Change to the format you want. The data structure is defined in the following format:

Type person struct {    /*tablename type is only used to set the table name. If the struct name is the same as the table name can be omitted */    TableName simpledb.tablename "    person"/*name is the table name, PK is used to set the primary key, true primary key, false non-primary key */    Id int ' Name: ' ID ' PK: ' True ' Auto: ' true ' '    name   string ' "Name '//tag Name table is the corresponding field name age    int    " age "  // The age table in tag is the corresponding field name    isboy  bool    notuse string "-"//-will not be saved to the database}

The above instructions are very detailed, simpledb.tablename type of field, only used in the tag to define the structure of the corresponding table name, if there is no such field, the table name is the same as the structure name. PK: "True" means the primary key, auto: "True" indicates that the field is an auto-growing column, name: "id", to specify the column name in the corresponding data table for that field, if it is not specified to be the same as the field name. When you only need to specify the column name, you can write directly in the tag, such as: "Name", "age". Tag is "-" to indicate that there are no columns in the corresponding data table.

Insert Data P: = &person{name: "Zhang San Fung", age:500, Isboy:true}db. Insert (p)//modify data db. Update (p)//delete data db. Delete (P)

Let's look at a complete example, first he creates a table:

CREATE TABLE ' person ' (    ' id ' int () ' is not null auto_increment,    ' name ' VARCHAR () null DEFAULT null,    ' age ' int ( Null DEFAULT null,    ' Isboy ' SMALLINT (Ten) null,    PRIMARY KEY (' id ')) collate= ' utf8_general_ci '; INSERT INTO ' Person ' (Name,age,isboy) VALUES (' Zhang San ', 20,0); insert INTO ' person ' (Name,age,isboy) VALUES (' Harry ', 19, 1);

The following is the complete code

Package Mainimport ("FMT" _ "Github.com/go-sql-driver/mysql" "github.com/male110/simpledb") type person struct { The/*tablename type is only used to set the table name. If the struct name is the same as the table name can be omitted */TableName simpledb.tablename "Person"/*name is the table name, PK is used to set whether the primary key, true primary key, false non-primary key */ID int ' name: "id" P     K: "True" Auto: "True" ' name string "name"//tag Name table is the corresponding field name age int "Age" in//tag the age table is the corresponding field name Isboy bool Notuse string "-"//-is not saved to the database}func main () {db, err: = simpledb.newdb ("MySQL", "root:123@tcp (127.0.0.1:3306)/test?"). Charset=utf8 ") if err! = Nil {fmt. PRINTLN ("Error opening sql:", err.) Error ()) return} defer db. Close () P: = &person{name: "Zhang Sanfeng", age:500, isboy:true}//Insert a data Err = db. Insert (P) if err! = Nil {fmt. PRINTLN (ERR) return} FMT. PRINTLN ("New Insert data Id:", p.id) var rows *simpledb.myrows//Fetch data from the database rows, err = db. Query ("SELECT * FROM person") if err! = Nil {fmt. PRINTLN (ERR) return}//displays data for rows. Next () {        var ID, age int var name string var isboy bool//field name to fetch data, or rows. Scan (&id,&name,&age) to fetch rows. GetValue ("id", &id) rows. GetValue ("name", &name) rows. GetValue ("Age", &age)//can determine if the success of err = rows is based on the return value. GetValue ("Isboy", &isboy) if err! = Nil {fmt. PRINTLN (ERR) return} FMT. Println (ID, "\ t", name, "\ T", age, "\ T", isboy)}//Output split line FMT. Println ("========== cut cut cut cut ============") P.name = "Pengzu" p.age = 800//Modify data _, Err = db. Update (P) if err! = Nil {fmt. Println (Err, "XXXX") return}//querydatarows returns a DataRow array with a map in the DataRow to hold the data in the row var arrrow []simpledb.dat Arow arrrow, err = db. Querydatarows ("SELECT * FROM person") if err! = Nil {fmt.        Println (Err, "Zzzzz") return} for _, Row: = Range Arrrow {var id, age int var name string var isboy bool//can only take data ro by field nameW.getvalue ("id", &id) row. GetValue ("name", &name) row. GetValue ("Age", &age)//can determine if the success of err = rows is based on the return value. GetValue ("Isboy", &isboy) if err! = Nil {fmt. PRINTLN (ERR) return} FMT. Println (ID, "\ t", name, "\ T", age, Isboy)} var p2 person p2. Id = p.id//Take a single data from the database based on the primary key err = db. Load (&P2) if err! = Nil {fmt. PRINTLN (ERR) return} FMT. Println (p2)//delete a data db based on the primary key. Delete (p2)}
Related Article

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.