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
推荐阅读
-
SQL Server、Oracle和MySQL判断NULL的方法
-
.net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式
-
ms sql server中实现的unix时间戳函数(含生成和格式化,可以和mysql兼容)
-
清晰讲解SQL语句中的外连接,通用于Mysql和Oracle,全是干货哦
-
Sql Server 2005的1433端口打开局域网访问和进行远程连接
-
SQL Server、MySQL和Sqlite获取表结构的方法
-
清晰讲解SQL语句中的外连接,通用于Mysql和Oracle,全是干货哦
-
清晰讲解SQL语句中的内连接,通用于Mysql和Oracle,全是干货哦
-
MySQL入门——MySQL数据库和SQL语言
-
Go语言中http和mysql的实现代码