1、创建数据库表
create table student (
id int NOT NULL AUTO_INCREMENT,
name varchar(20),
age int
)
2、添加数据
insert into student values(1001,"lena",21),(1002,"titiy",22);
3、go get mysql
如果是第一次连接mysql数据库,需要先拉取mysql所需要的包 go get -u github.com/go-sql-driver/mysql 该过程我遇到了一个代理失败的error,如相同可参考:https://blog.csdn.net/lena7/article/details/120254809
4、Golang测试连接数据库
由于在实际中并未使用到mysql的包,但在sql.Open 中传入mysql会自动查找mysql ,并不是直接使用到,我使用的工具Goland会自动将未直接使用导包删除掉,因此我们可以在mysql的导包前面加_ 。
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func ConnMysql() {
url := "root:root@tcp(127.0.0.1:3306)/test"
db, err := sql.Open("mysql", url)
if err != nil {
fmt.Println("conn err :",err)
return
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Println("ping err :",err)
return
}
fmt.Println("conn success!")
}
如果连接失败,可以进行以下尝试:
- 首先打开电脑的命令行模式,输入
mysql 看看是否有信息,如果没有,可能是未启动mysqld服务、没有配置环境变量等原因。 - 使用命令
mysql -u 账号 -p 回车后输入密码,查看是否能够进入数据库。如果在命令行能够进入,连接应该没什么问题。
CRUD操作
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"fmt"
)
var db *sql.DB
func Conn() {
url := "root:root@tcp(127.0.0.1:3306)/test"
db, _ = sql.Open("mysql", url)
err := db.Ping()
if err != nil {
fmt.Println("ping err :",err)
return
}
fmt.Println("conn success!")
}
type Student struct {
id int
name string
age int
}
func QueryOne(id int) Student {
sql := "select * from student where id = ?"
s:=Student{}
err := db.QueryRow(sql,id).Scan(&s.id, &s.name, &s.age)
if err != nil {
fmt.Println("select err :",err)
}
return s
}
func QueryAgeMore(age int) []Student {
sql := "select * from student where age > ?"
rows, err := db.Query(sql, age)
if err != nil {
fmt.Println("select err :",err)
return nil
}
defer rows.Close()
var students []Student
for rows.Next() {
var s Student
err := rows.Scan(&s.id, &s.name, &s.age)
if err != nil {
fmt.Println("scan err :",err)
break
}
students=append(students, s)
}
return students
}
func Insert(s Student) int {
sql := "insert into student(name,age) values(?,?)"
res, err := db.Exec(sql,s.name, s.age)
if err != nil {
fmt.Println("insert err :",err)
return 0
}
id, err := res.LastInsertId()
if err != nil {
fmt.Println("get last id err :",err)
return s.id
}
return int(id)
}
func UpdateOne(s Student) int {
sql := "update student set age = ? where id = ?"
res, err := db.Exec(sql, s.age, s.id)
if err != nil {
fmt.Println("update err :",err)
return 0
}
i, err := res.RowsAffected()
if err != nil {
fmt.Println("get effected row num err :",err)
return 0
}
return int(i)
}
func DeleteOne(id int) int {
sql := "delete from student where id = ?"
res, err := db.Exec(sql, id)
if err != nil {
fmt.Println("delete err :",err)
return 0
}
i, err := res.RowsAffected()
if err != nil {
fmt.Println("get effected row num err :",err)
return 0
}
return int(i)
}
测试代码
import (
"fmt"
"reflect"
"testing"
)
func TestQueryOne(t *testing.T) {
Conn()
s := QueryOne(1001)
var expert=Student{1001,"lena",21}
if !reflect.DeepEqual(s,expert) {
t.Errorf("result is %v,not expert %v",s,expert)
}
}
func TestQueryAgeMore(t *testing.T) {
Conn()
s := QueryAgeMore(10)
fmt.Println(s)
}
func TestInsert(t *testing.T) {
Conn()
s:=Student{0,"tity",15}
res := Insert(s)
if !reflect.DeepEqual(res,1005) {
t.Errorf("res = %v",res)
}
}
func TestUpdateOne(t *testing.T) {
Conn()
s:=Student{1004,"peity",18}
i := UpdateOne(s)
if !reflect.DeepEqual(i,1) {
t.Errorf("reflected row : %v",i)
}
}
func TestDeleteOne(t *testing.T) {
Conn()
i := DeleteOne(1005)
if !reflect.DeepEqual(i,1) {
t.Errorf("reflected row : %v",i)
}
}
|