Beego: natively with MySQL

Example:

Controllers Package 

Import (
     "Database / SQL" 
    "FMT" 
    "github.com/astaxie/beego" 
    _ "github.com/go-sql-driver/mysql" 
) 

type struct {MysqlController 
    beego.Controller 
} 

FUNC (C * MysqlController) GET () {
     // connect to the database 
    db, ERR: = sql.Open ( "MySQL", "root:? Pd940810 @ tcp (127.0.0.1:3306) / the Test charset = utf8" )
     IF ERR =! nil { 
        beego. info ( "database connection error" , ERR)
         return 
    } 
    // close the database connection 
    the defer db.Close () 

    // create a table
    _, ERR = db.Exec ( "Create the userInfo Table (int Not null AUTO_INCREMENT ID Primary Key, name VARCHAR (. 11) UNIQUE)" )
     IF ! ERR = nil { 
        fmt.Printf ( "create table Error:% V" , ERR )
         return 
    } 

    // insert data 
    _, err = db.Exec ( "insert into userInfo (name) values (?)", " George" )
     IF ERR =! nil { 
        fmt.Printf ( "create table error:% v" , ERR)
         return 
    } 

    // query data 
    rows, err: = db.Query ( " select * from userInfo")
    type UserInfo struct {
        Id int
        Name string
    }
    var u UserInfo
    for rows.Next() {
        err = rows.Scan(&u.Id, &u.Name)
        fmt.Println(u)
    }

    // 更新数据
    _, err = db.Exec("update userInfo set name='pd' where id=1")

    c.Ctx.WriteString("testing...")
}
controllers/mysql.go

 

Guess you like

Origin www.cnblogs.com/believepd/p/11006126.html