Golang 调用MySQL存储过程

最近写项目发现,很多逻辑业务的实现,写到数据库的存储过程中,然后调用,真的非常方便。后端代码量大大减少,最重要的是性能高,速度快!

引用说明:项目使用数据库ORM xorm(附地址)

存储过程代码 demo:

数据库名:user

表名:student

create table student

(

id int auto_increment primary key,

name varchar(10) null,

age int null comment '年龄',

gender tinyint null comment '性别<1:男/2:女>',

phone varchar(15) null,

address varchar(50) null

);

insert into student (name, age, gender, phone, address) values ('Jerry',28,1,'13812341234','上海市');

存储过程 demo

-- 创建存储过程

create procedure query_student(IN i_name varchar(10),

IN i_gender tinyint,

OUT o_id int,

OUT o_name varchar(10),

OUT o_age int,

OUT o_gender tinyint,

OUT o_phone varchar(15),

out o_address varchar(50))

comment '根据名字和性别查询学生信息'

begin

-- 搜索信息并赋值

select student.id,

student.name,

student.age,

student.gender,

student.phone,

student.address

into o_id,o_name,o_age,o_gender,o_phone,o_address

from student

where student.name = i_name

and student.gender = i_gender;

-- 返回结果需要返回的结果

select o_id,o_name,o_age,o_gender,o_phone,o_address;

end;

Golang代码 demo:

代码:

var engine *xorm.Engine

func InitMySQL(dbDsn string) {

var err error

engine, err = xorm.NewEngine("mysql", dbDsn)

if err != nil {

panic(err)

}

engine.ShowSQL(true)

}

func MySQL() *xorm.Engine {

return engine

}

InitMySQL("user:password@tcp(127.0.0.1:3306)/user?charset=utf8")

queryString, err := MySQL().QueryString("call user.query_student(?,?,@1,@2,@3,@4,@5,@6)", "Jerry", 1)

if err != nil {

log.Println("err:", err)

}

for k, v := range queryString[0] {

fmt.Printf("columns:%v - value:%v\n", k, v)

}

输出结果

columns:o_name - value:Jerry

columns:o_age - value:28

columns:o_gender - value:1

columns:o_phone - value:13812341234

columns:o_address - value:上海市

columns:o_id - value:1

以上只是做了个最简单的demo,如果遇到更复杂的搜索情况,靠存储过程实现,效率非常可观!

标签:调用,varchar,name,err,gender,Golang,student,MySQL,columns