go language basic link MySQL

Insert operation:
step1: import the package
"database/sql"
_ "github.com/go-sql-driver/mysql"
step2: open the database and establish a connection
db,_:=sql.Open("mysql","root:xxx @tcp(127.0.0.1:3306)/my1802?charset=utf8") // xxx is the password
step3: Operation database:
stmt_:=db.Prepare("sql .... ?,?")
result,_:= stmt.Exec (assign?)
step4: Operation result object
result.LastIndexId()-->int64
result.RowsAffected()-->int64
step5: Close resource
stmt.Close()

db.Close()

package main
// step1:导入包
import (
   "database/sql"
   _"github.com/go-sql-driver/mysql"
   "fmt"
)

func main () {
    // step2: Open the database, which is equivalent to establishing a connection with the database: db object
    /*
    func Open(driverName, dataSourceName string) (*DB, error)
    drvierName, "mysql"
    dataSourceName, username: password@protocol (address:port)/database?parameter=parameter value
     */
    db , err:=sql.Open( "mysql" , "root:hanru1314@tcp(127.0.0.1:3306)/my1802?charset=utf8" )
    if err !=nil{
      fmt.Println( "Connection failed.." )
       return
    }
    //step3: Insert a piece of data
 stmt , err:=db.Prepare( "INSERT INTO emp(empno,ename,job,hiredate,sal) values(?,?, ?,?,?)" )
    if err !=nil{
   
      fmt.Println( "The operation failed.." )
   }
   //Complete the complete sql statement and execute
    result , err:=stmt.Exec( 9530 , "Small Drill Wind" , "Mountain Patrol " , "2018-04-21" , 30.8 )
    if err !=nil{
      fmt.Println( "Failed to insert data.." )
   }
   //step4: process the result after sql operation
    lastInsertId , err:=result.LastInsertId()
   rowsAffected,err:=result.RowsAffected()
   fmt.Println("lastInsertId",lastInsertId)
   fmt.Println( "Number of rows affected:" , rowsAffected)


   //Insert data again:
    result , _=stmt.Exec( 9531 , " White Bone Spirit" , "Mountain Patrol" , " 2017-11-11 " , 50.8 )
   count,_:=result.RowsAffected()
   fmt.Println( "Number of lines affected: " , count)




   //step5: Close the resource
    stmt.Close()
   db.Close()


}

Query database: DQL language
step1: same as above, import package
step2: same as above, establish connection
step3: query
rows, err:=db.Query("select....", the replacement value of placeholder)
step4: process the query to The data
rows.Colums()-->the name of the queried field []string
rows.Next()-->bool, determine whether there is the next value
rows.Scan(&variable name, &....)

package main
//step1:导入包
import (
   "database/sql"
   _ "github.com/go-sql-driver/mysql"
   "fmt"
)
type Emp struct {
   Empno int
   Ename string
   Job string
   Hiredate string
   Sal float64
   Deptno int
}

func main()  {
   /*
   查询操作:
    */
   //step2:打开数据库,建立连接
   db,_ := sql.Open("mysql","root:hanru1314@tcp(127.0.0.1:3306)/my1802?charset=utf8")

   //stpt3:查询数据库
   rows,err:=db.Query("SELECT empno,ename,job,hiredate,sal,deptno FROM emp WHERE deptno=?",30)
   fmt.Println("--->",err.Error())
   fmt.Println(rows.Columns()) //[empno ename job hiredate sal deptno]
   //思路一:定义一个map,用于存储从数据库中查询出来的数据,字段作为key,string,数据作为value,任意类型,空接口
   map1:=make(map[string]interface{})
   datas := make([] map[string]interface{},0)

   //思路二:创建slice,存入struct,
   datas2:=make([] Emp,0)
   //step4:操作结果集获取数据
   for rows.Next(){
      var empno int
      var ename string
      var job string
      var hiredate string
      var sal float64
      var deptno int
      if err:=rows.Scan(&empno,&ename,&job,&hiredate,&sal,&deptno);err!=nil{
         fmt.Println("获取失败。。")
      }
      //fmt.Println(empno,ename,job,hiredate,sal,deptno)
      //将读取到的数据,存入了map中
      map1["empno"]=empno
      map1["ename"]=ename
      map1["job"]=job
      map1["hiredate"]=hiredate
      map1["sal"]=sal
      map1["deptno"]=deptno
      //将map存入切片中
      datas = append(datas,map1)


      //思路二:每读取一行,创建一个emp对象,存入datas2中
      emp := Emp{empno,ename,job,hiredate,sal,deptno}
      datas2 =append(datas2, emp)
   }
   //step5:关闭资源
   rows.Close()
   db.Close()

   //遍历切片
   //fmt.Println("empno\tename\tjob\thiredate\tsal\tdeptno")
   //for _,v:=range datas{
   // for _,val:=range v{
   //    fmt.Print(val,"\t")
   //}
   //fmt.Println()
   //
   //}

   for _,v:=range  datas2{
      fmt.Println(v)
   }


}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325942686&siteId=291194637