首页 > 数据库 >Golang MySQL 操作

Golang MySQL 操作

时间:2023-05-08 21:23:14浏览次数:42  
标签:err DB fmt db Golang inst user MySQL 操作

1 .   创建go_db 目录

           mkdir go_db

2. 

root@VirtualBox:/mnt/share/goframe/go_db# go mod init go_db
go: creating new go.mod: module go_db
root@VirtualBox:/mnt/share/goframe/go_db# go get -u github.com/go-sql-driver/mysql
go: added github.com/go-sql-driver/mysql v1.7.1
root@VirtualBox:/mnt/share/goframe/go_db#

3   

root@wally-VirtualBox:/mnt/share/goframe/go_db# go run mysql_go.go
db reachable, *sql.DB, *main.DB_INSTANCE
after fetch
id 1, username user2, password pass3, create_at 2023-05-08 15:47:01
after fetchall
id, username, password, create_at
1, user2, pass3, 2023-05-08 15:47:01
3, user3, pwd3, 2023-05-08 17:46:00
[]main.User{main.User{id:1, username:"user2", password:"pass3", createAt:1683532021}, main.User{id:3, username:"user3", password:"pwd3", createAt:1683539160}}
after fetchall
id, username, password, create_at
1, user2, pass3, 2023-05-08 15:47:01
3, user3, pwd3, 2023-05-08 17:46:00
[]main.User{main.User{id:1, username:"user2", password:"pass3", createAt:1683532021}, main.User{id:3, username:"user3", password:"pwd3", createAt:1683539160}}

   如下为 mysql_go.go ,其中,fetchall 获取的用户通过值传递。

package main

import (
   "database/sql"
   "fmt"
   _ "github.com/go-sql-driver/mysql"
   "log"
   "time"
)

const DB_ADDR_PORT = "localhost:3307"
const DB_LOGIN_USER = "root"
const DB_LOGIN_PASS = "usbw"
const DB_TAB = "test"

type DB_INSTANCE struct {
   db *sql.DB
}

type User struct {
   id       int
   username string
   password string
   createAt int
}

type USER_LIST_ST struct {
   users_list []User
}

func db_init() *DB_INSTANCE {
   dsn := fmt.Sprintf("%s:%s@(%s)/%s", DB_LOGIN_USER, DB_LOGIN_PASS, DB_ADDR_PORT, DB_TAB)
   db, err := sql.Open("mysql", dsn)

   if err != nil {
      log.Fatalf("connect db failed %v", err)
      return nil
   }

   if err := db.Ping(); err != nil {
      log.Fatalf("ping db failed %v", err)
      return nil
   }

   db_inst := new(DB_INSTANCE)
   db_inst.db = db

   //fmt.Printf("db reachable, %T, %T, %#v\n", db, db_inst, db)
   fmt.Printf("db reachable, %T, %T\n", db, db_inst)

   return db_inst
}

func (db_inst *DB_INSTANCE) db_insert() bool {
   query := `
               CREATE TABLE IF NOT EXISTS users(
               id INT UNSIGNED AUTO_INCREMENT,
               username VARCHAR(255) NOT NULL,
               password VARCHAR(255) NOT NULL,
               create_at INT(10) NOT NULL,
               PRIMARY KEY (id)
            )ENGINE=INNODB DEFAULT CHARSET=UTF8;
   `

   _, err := db_inst.db.Exec(query)

   if err != nil {
      log.Fatalf("user create failed %v", err)
      return false
   }

   for i := 1; i < 5; i++ {

      username := fmt.Sprintf("user%d", i)
      password := fmt.Sprintf("pwd%d", i)
      createAt := time.Now().Unix()

      rv, err := db_inst.db.Exec(`INSERT INTO users (username, password, create_at) VALUES(?, ?, ?)`, username, password, createAt)
      if err != nil {
         log.Fatalf("insert failed %v", err)
         return false
      }

      uid, err := rv.LastInsertId()

      fmt.Printf("inserted %d\n", uid)
   }

   return true
}

func (db_inst *DB_INSTANCE) db_fetch() (bool, *User) {
   user := new(User)

   query := `SELECT id, username, password, create_at FROM users WHERE id=?`
   err := db_inst.db.QueryRow(query, 1).Scan(&user.id, &user.username, &user.password, &user.createAt)

   if err != nil {
      log.Fatalf("queryrow failed %v", err)
      return false, &User{}
   }

   return true, user
}

func (db_inst *DB_INSTANCE) db_fetchall() (bool, *USER_LIST_ST) {
   query := `SELECT id, username, password, create_at FROM users WHERE id < ? LIMIT ?`
   rows, err := db_inst.db.Query(query, 20, 2)
   if err != nil {
      return false, &USER_LIST_ST{}
   }

   defer rows.Close()

   var user_list USER_LIST_ST
   for rows.Next() {
      u := User{}
      err := rows.Scan(&u.id, &u.username, &u.password, &u.createAt)
      if err != nil {
         continue
      }

      user_list.users_list = append(user_list.users_list, u)
   }

   err = rows.Err()

   if err != nil {
      log.Fatalf("fetchall failed %v", err)
      return false, &USER_LIST_ST{}
   }

   return true, &user_list
}

func (db_inst *DB_INSTANCE) db_delete() bool {
   query := `DELETE FROM users WHERE id=?`

   _, err := db_inst.db.Exec(query, 2)
   if err != nil {
      log.Fatalf("delete failed %v", err)
      return false
   }

   return true
}

func (db_inst *DB_INSTANCE) db_update() bool {
   query := `update users set username=?,password=? WHERE id=?`
   r, err := db_inst.db.Exec(query, "user2", "pass3", 1)

   if err != nil {
      log.Fatalf("update failed %v", err)
      return false
   }

   row, err := r.RowsAffected()
   if err != nil {
      log.Fatalf("update rows failed %v", err)
      return false
   }

   fmt.Println("RowsAffected ", row)

   return true
}

func (user *User) print() {
   timeObj := time.Unix(int64(user.createAt), 10)

   fmt.Printf("id %d, username %s, password %s, create_at %s\n", user.id, user.username, user.password,
      timeObj.Format("2006-01-02 15:04:05"))
}

func (users *USER_LIST_ST) prints() {
   fmt.Printf("id, username, password, create_at \n")

   for _, user := range users.users_list {

      timeObj := time.Unix(int64(user.createAt), 10)

      fmt.Printf("%d,  %s,  %s,  %s\n", user.id, user.username, user.password,
         timeObj.Format("2006-01-02 15:04:05"))
   }

   fmt.Printf("%#v\n", users.users_list)
}

func main() {

   db_inst := db_init()
   if db_inst == nil {
      fmt.Println("db init failed ")
      return
   }

   /*
      rv := db_inst.db_insert()
      if !rv {
         fmt.Println("db insert failed")
      }
   */

   fmt.Println("after fetch")
   rv, user := db_inst.db_fetch()
   if !rv {
      fmt.Println("db fetch failed")
      return
   }

   user.print()

   fmt.Println("after fetchall")
   rv, users := db_inst.db_fetchall()
   if !rv {
      fmt.Println("db fetchall failed")
      return
   }

   users.prints()

   /*
      fmt.Println("after delete")

         rv = db_inst.db_delete()
         if !rv {
            fmt.Println("delete failed")
            return
         }
   */

   /*
      fmt.Println("after update")
      rv = db_inst.db_update()
      if !rv {
         fmt.Println("update failed")
      }
   */

   fmt.Println("after fetchall")
   rv, users = db_inst.db_fetchall()
   if rv {

      users.prints()
   }

}

 

  如下fetchall中user为通过指针传递。

package main

import (
   "database/sql"
   "fmt"
   _ "github.com/go-sql-driver/mysql"
   "log"
   "time"
)

const DB_ADDR_PORT = "localhost:3307"
const DB_LOGIN_USER = "root"
const DB_LOGIN_PASS = "usbw"
const DB_TAB = "test"

const MAX_BUF_SIZE = 100

type DB_INSTANCE struct {
   db *sql.DB
}

type User struct {
   id       int
   username string
   password string
   createAt int
}

type USER_LIST struct {
   users_ptr [MAX_BUF_SIZE]*User
}

func db_init() *DB_INSTANCE {
   dsn := fmt.Sprintf("%s:%s@(%s)/%s", DB_LOGIN_USER, DB_LOGIN_PASS, DB_ADDR_PORT, DB_TAB)
   db, err := sql.Open("mysql", dsn)

   if err != nil {
      log.Fatalf("connect db failed %v", err)
      return nil
   }

   if err := db.Ping(); err != nil {
      log.Fatalf("ping db failed %v", err)
      return nil
   }

   db_inst := new(DB_INSTANCE)
   db_inst.db = db

   //fmt.Printf("db reachable, %T, %T, %#v\n", db, db_inst, db)
   fmt.Printf("db reachable, %T, %T\n", db, db_inst)

   return db_inst
}


func (db_inst *DB_INSTANCE) db_fetchall() (bool, *USER_LIST, int) {
   query := `SELECT id, username, password, create_at FROM users WHERE id < ? LIMIT ?`
   rows, err := db_inst.db.Query(query, 20, 2)
   if err != nil {
      return false, &USER_LIST{}, 0
   }

   defer rows.Close()

   count := 0
   var user_list USER_LIST

   for rows.Next() {
      u := User{}
      err := rows.Scan(&u.id, &u.username, &u.password, &u.createAt)
      if err != nil {
         continue
      }

      user_list.users_ptr[count] = &u
      count++
   }

   err = rows.Err()

   if err != nil {
      log.Fatalf("fetchall failed %v", err)
      return false, &USER_LIST{}, 0
   }

   return true, &user_list, count
}


func (user_list *USER_LIST) prints(count int) {
   fmt.Printf("id, username, password, create_at \n")

   for j := 0; j < count; j++ {
      user := user_list.users_ptr[j]

      timeObj := time.Unix(int64(user.createAt), 10)

      fmt.Printf("%d,  %s,  %s,  %s\n", user.id, user.username, user.password,
         timeObj.Format("2006-01-02 15:04:05"))
   }
}

 

标签:err,DB,fmt,db,Golang,inst,user,MySQL,操作
From: https://www.cnblogs.com/wallywl/p/17383191.html

相关文章

  • 关于使用kubeadm reset命令对kubeadm init与kubeadm join操作后遇到报错的情况-进行恢
    在Kubernetes/k8s集群中,无论是在开始的master节点初始化,还是后面客户端使用kubeadmjoin命令加入到集群可能都会遇到很多报错,对于新手来说、很多还不是很好解决、也有一些情况,是在初始化之前忘记执行一些操作,而导致报错这种一般都需要执行漏掉的操作,重新执行初始化操作,但是如......
  • golang map key struct hash policy
     Theeasiestandmostflexiblewayistousea struct asthekeytype,includingallthedatayouwanttobepartofthekey,soinyourcase:typeKeystruct{X,Yint}Andthat'sall.Usingit:m:=map[Key]int{}m[Key{2,2}]=4m[Key{2......
  • 项目创始者和开发者操作
    1.电脑指定位置拉取代码: 2.进入拉取文件夹输入gitlog即可查看之前的操作日志: 3.截至提交到版本库的流程: 4.提交到远程仓库: 5.从远程仓库拉取代码: 6.c.txt文件中修改内容,提交到远程仓库: 7.协同开发: 8.总结: ......
  • Mysql面试题
    1.Mysql基础1、from子句组装来自不同数据源的数据;2、where子句基于指定的条件对记录行进行筛选;3、groupby子句将数据划分为多个分组;4、使用聚集函数进行计算;5、使用having子句筛选分组;6、计算所有的表达式;7、select的字段;8、使用orderby对结果集进行排序。SQL语言不同......
  • MySQL主从
    MySQL主从一主从复制介绍1.1什么是主从复制将主服务器的binlog日志复制到从服务器上执行一遍,达到主从数据的一致状态,称之为主从复制。一句话表示就是,主数据库做什么,从数据库就跟着做什么。1.2为何要做主从(1)为实现服务器负载均衡/读写分离做铺垫,提升访问速度#1、什么......
  • MySQL面试手册
    面试手册1、你接触过哪几种数据库软件,各自的优缺点是什么?2、MySQLbinlog的几种日志格式有什么区别?3、MySQL的存储引擎有哪几种?4、MySQL主从复制原理是什么?5、MySQL中myisam和innodb的区别?6、字段类型varchar和char的区别是什么?varchar(50)中50代表什么?7、关系型数据库和非......
  • MySQL锁机制
    一数据库的锁机制什么是锁?为何要加入锁机制?锁是计算机协调多个进程或线程并发访问某一资源的机制,那为何要加入锁机制呢?因为在数据库中,除了传统的计算资源(如CPU、RAM、I/O等)的争用以外,数据也是一种供需要用户共享的资源。当并发事务同时访问一个共享的资源时,有可能导致数据不......
  • MySQL日志管理
    MySQL日志管理一日志分类日志种类作用错误日志记录MySQL服务器启动、关闭及运行错误等信息事务日志1、redolog重做日志2、undolog回滚日志查询日志记录所有的sql慢查询日志记录执行时间超过指定时间的操作,如果是全表查询,即便没有超时也会被记录下......
  • MySQL基本管理
    数据库基本管理一MySQL启动关闭流程mysql是一个典型的C/S服务结构1.mysql自带的客户端程序(/service/mysql/bin) mysql mysqladmin mysqldump2.mysqld一个二进制程序,后台的守护进程 单进程 多线程1.1启动数据库1、/etc/init.d/mysqldstart--->mysql.server--->......
  • 操作系统 | OS
    1操作系统简介1.1操作系统的定义与功能操作系统指的是从计算机加电运行后一直在内存运行的程序,又称“内核”.它负责管理计算机硬件和软件资源,同时为用户和应用程序提供一个友好的交互界面.操作系统的主要功能包括进程管理,内存管理,文件系统管理,设备管理,用户界面......