Chinaunix首页 | 论坛 | 博客
  • 博客访问: 494615
  • 博文数量: 224
  • 博客积分: 2175
  • 博客等级: 大尉
  • 技术积分: 2433
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-05 22:02
个人简介

目前在一家公司担任软件总监,主要涉及智能手机,笔记本电脑的开发

文章分类

全部博文(224)

文章存档

2024年(5)

2023年(68)

2022年(13)

2021年(7)

2020年(11)

2019年(3)

2018年(10)

2017年(8)

2012年(7)

2011年(4)

2010年(32)

2009年(41)

2008年(6)

2007年(9)

分类: 云计算

2022-04-27 00:03:06

一 当mysql数据库建立后,
二 使用go,对mysql数据库进行操作。
   有两种方式,使用grom 和 sqlx;
1:使用第三方开源的mysql库: github.com/go-sql-driver/mysql (mysql驱动) github.com/jmoiron/sqlx (基于mysql驱动的封装)
   安装:
       go mod init gotest

     go get  github.com/go-sql-driver/mysql@latest

         go get  github.com/jmoiron/sqlx@latest
    安装失败解决:
      默认使用的是proxy.golang.org,在国内无法访问;使用国内的代理:     
 go env -w GOPROXY=https://goproxy.cn 
     这样就解决了go包管理代理网址无法访问的问题。

案例如下:
      
package main

import (
"fmt"

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

//数据库指针
var db *sqlx.DB

//初始化数据库连接,init()方法系统会在动在main方法之前执行。
func init() {
database, err := sqlx.Open("mysql", "root@tcp(127.0.0.1:3306)/projectres")
if err != nil {
fmt.Println("open mysql failed,", err)
}
db = database
}

func main() {

sql := "insert people(name,organization_idorganization ) values (?,?)"
value := [2]string{"user 01", "5"}

//执行SQL语句
r, err := db.Exec(sql, value[0], value[1])
if err != nil {
fmt.Println("exec failed,", err)
return
}

//查询{BANNED}最佳后一天用户ID,判断是否插入成功
id, err := r.LastInsertId()
if err != nil {
fmt.Println("exec failed,", err)
return
}
fmt.Println("insert succ", id)

}

go build hello.go
      ./hello

2 使用gorm
   安装gorm:

      go mod init gotest

      go get github.com/jinzhu/gorm@latest



阅读(565) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~