欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言连接MySQL和SQL Server

程序员文章站 2022-04-18 14:24:00
连接MySQL,先获取第三方包go get -u github.com/go-sql-driver/mysql连接SQL Server,获取第三方包go get github.com/mattn/go-adodb# 安装以下包,不然报错 cannot find package "golang.org/x/sys/unix"mkdir -p $GOPATH/src/golang.org/xcd $GOPATH/src/golang.org/x...

1 连接MySQL

先获取第三方包

go get -u github.com/go-sql-driver/mysql

代码如下

package main

import (
	"database/sql"
	"fmt"

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

const (
	userName = "rsq"
	password = "123456"
	ip = "192.168.1.100"
	port = "3306"
	dbName = "test"
)
func connInsert(BillMonth string, BusinessCodeName string, RealTotalCost float64) {

	// 构建连接:"用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
	dbInfo := strings.Join([]string{userName, ":", password, "@tcp(",ip, ":", port, ")/", dbName, "?charset=utf8"}, "")

	// 打开数据库,前者是驱动名,所以要导入: _ "github.com/go-sql-driver/mysql"
	db, err := sql.Open("mysql", dbInfo)
	if err != nil {
		fmt.Println("Open database Error:", err)
	}

	// 插入操作
	insert, err := db.Exec("INSERT INTO student (Name,Age,Score) VALUES (?, ?, ?)", "tom", 18, 88.5)
	if err != nil {
		fmt.Println("Insert data err=", err)
	}
	id, err := insert.LastInsertId()
	fmt.Printf("成功插入, id是%v\n", id)

}

2 连接SQL Server

获取第三方包

go get github.com/mattn/go-adodb

# 安装以下包,不然报错 cannot find package "golang.org/x/sys/unix"
mkdir -p $GOPATH/src/golang.org/x
cd $GOPATH/src/golang.org/x
git clone https://github.com/golang/sys.git
git clone https://github.com/golang/net.git

# windows下直接去github获取zip包,解压放到 $GOPATH/src/golang.org/x/目录 即可

代码如下

package main

import (
	"database/sql"
	"fmt"

	_ "github.com/mattn/go-adodb"
)

func TestSqlServer(BillMonth string, BusinessCodeName string, RealTotalCost float64) {
	var conf []string
	var db *sql.DB
	var err error
	conf = append(conf, "Provider=SQLOLEDB")
	conf = append(conf, "Data Source=192.168.1.100")  // sqlserver IP 和 服务器名称
	conf = append(conf, "Initial Catalog=test") // 数据库名
	conf = append(conf, "user id=rsq") // 登陆用户名
	conf = append(conf, "password=123456")  // 登陆密码
	//fmt.Println(strings.Join(conf, ";"))
	
	// 连接数据库
	db, err = sql.Open("adodb", strings.Join(conf, ";"))
	if err != nil {
		fmt.Println("sql open:", err)
		return
	}

	// 插入数据
	insert, err := db.Exec("INSERT INTO student (Name,Age,Score) VALUES (?, ?, ?)", "tom", 18, 88.5)
	if err != nil {
		fmt.Println("Insert data err=", err)
	}
	fmt.Println("成功插入数据!")

}

本文地址:https://blog.csdn.net/Mr_rsq/article/details/107383629