当前位置: 首页 > 工具软件 > GoMySQL > 使用案例 >

GO中使用MySQL《查询》

令狐运珧
2023-12-01

查询:

第一种:

建立数据库连接:
package mysql
import (
   "database/sql"
   "fmt"
   _ "github.com/go-sql-driver/mysql"
   "os"
)
var db *sql.DB
func init() {
   db, _ = sql.Open("mysql", "fu:123@tcp(127.0.0.1:3306)/fileserver?charset=utf8")
   db.SetMaxOpenConns(1000)
   err := db.Ping()
   if err != nil {
      fmt.Println("Failed to connect mysql , err :" + err.Error())
      os.Exit(1)
   } else {
      fmt.Println("连接成功")
   }
}

//DBconn:返回数据库连接对象
func DBConn() *sql.DB {
   return db
}
调用数据库连接的方法:
package db

import (
   "database/sql"
   "fmt"
   mydb "FBSyuncunchuxitong/db/mysql"
)
type TableFile struct {
   FileHash string
   FileName sql.NullString
   FileSize sql.NullInt64
   FileAddr sql.NullString
}
//从mysql获取文件信息
func GetFileMeta(filehash string)(*TableFile,error)  {
   stmt, err := mydb.DBConn().Prepare(
      "select file_sha1,file_addr,file_name,file_size from tbl_file " +
         "where file_sha1=? and status=1 limit 1")
   if err !=nil {
      fmt.Println("查询错误:"+err.Error())
      return nil, err
   }
   defer stmt.Close()

   tfile :=TableFile{}
   err = stmt.QueryRow(filehash).Scan(
      &tfile.FileHash,&tfile.FileAddr,&tfile.FileName,&tfile.FileSize)
   if err !=nil{
      fmt.Println("给参数时候错误:"+err.Error())
      return nil, err
   }
   return &tfile,nil
}

第二种 :

package main

import (
   "fmt"

   _ "github.com/go-sql-driver/mysql"
   "github.com/jmoiron/sqlx"
)

type Person struct {
   UserId   int    `db:"user_id"`
   Username string `db:"username"`
   Sex      string `db:"sex"`
   Email    string `db:"email"`
}

var Db *sqlx.DB

func init() {
   database, err := sqlx.Open("mysql", "root:123@tcp(127.0.0.1:3306)/test")
   if err != nil {
      fmt.Println("open mysql failed,", err)
      return
   }
   Db = database
}

func main() {
   var person []Person
   err := Db.Select(&person, "select user_id, username, sex, email from person where user_id=?", 1)
   if err != nil {
      fmt.Println("exec failed, ", err)
      return
   }
   fmt.Println("select succ:", person)
}
 类似资料: