登录
首页 >  Golang >  Go问答

使用Golang从PostgreSQL函数中获取多个值,其中函数返回整数并接受字符串数组

来源:stackoverflow

时间:2024-03-07 19:27:26 388浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《使用Golang从PostgreSQL函数中获取多个值,其中函数返回整数并接受字符串数组》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我有一个 postgresql 函数,它基本上返回一个数字,而且正如您所看到的,该函数接收一个字符串数组。

create or replace function fnregisteruserrolearray(iduserfather int, rolesarray text[]) returns int language plpgsql
as
$body$
declare ids int;
declare roleid int;
declare sanitazedrole text;
declare counter int = 0;
begin
if(empty2null(iduserfather::text) is null) then
    ids := 0;
elsif exists( select 1 from win_users where id_user = iduserfather limit 1) then
    for counter in 1 .. array_upper(rolesarray, 1)
    loop
        select id_role from win_roles where rolename = rolesarray[counter] into roleid;
        insert into win_user_role(id_user, id_role) values (iduserfather, roleid);
        ids := ids + 1;
    end loop;
else
    ids := 0;
end if;
return ids;
end $body$;

在我的 go 函数中,我有一个变量数据库,它接收与 postgresql 数据库的连接,

database, err := getconnection()

但是,当我调用函数 fnregisteruserviewspermission 并发送值时,我收到错误。

这就是我设置值的方式:

var resultRole int 
err = database.QueryRow("Select fnRegisterUserRoleArray($1, $2);", resultUser, pq.Array(roleArray)).Scan(&resultRole, &int)
    fmt.Println(resultRole)
    if err != nil {
        fmt.Println(resultRole)
        return nil, err
    }
    if resultRole != 0 && resultRole != 1 {
        response = response + "their roles has been assigned correctly "
    } else {
            response = response + "however there was an error during the assignation of the role."
    }

我收到的输出是这样的:

"message": "sql: 列索引 0 上扫描错误:转换 driver.value 将 (\"\") 键入 int:无效语法",

但是这些值存储在我的数据库中,因此该函数可以很好地接收这些值,但返回的是它要去的地方 bam :(

这只发生在我发送数组时,但如果我发送任何内容而不是数组,扫描器将返回从 postgresql 函数获得的 id。

有没有办法既能获取结果id,又能以更优雅的方式发送数组?

这是包含角色数组的值:

[运营商品牌]

包含 resultuser 的值只是一个数字,代表已在数据库中注册的用户的 id,在本例中注册用户的 id 为...

结果用户:63

谢谢! :)


解决方案


正如错误所示:

"message": "sql: 列索引 0 上扫描错误:转换 driver.value 将 (\"\") 键入 int:无效语法",

错误是在从函数返回值时扫描来自函数的结果时发生的。

删除指向 int 基元类型的指针,因为 int 类型的函数仅返回单个值。

将值扫描成int类型变量为

var resultrole int 
err = database.queryrow("select fnregisteruserrolearray($1, $2);", resultuser, pq.array(rolearray)).scan(&resultrole)

为了处理这些类型的情况,最好将扫描结果与查询分开处理,如下所示:

sqlStatement := `Select fnRegisterUserRoleArray($1, $2);`
var resultRole int 
// Replace 3 with an ID from your database or another random
// value to test the no rows use case.
row := db.QueryRow(sqlStatement, resultUser, pq.Array(roleArray))
switch err := row.Scan(&resultRole); err {
case sql.ErrNoRows:
  fmt.Println("No rows were returned!")
case nil:
  fmt.Println(resultRole)
default:
  panic(err)
}

使用上述将 queryrow 与 scan 分开的方法可以帮助您更多地分析结果和返回的错误。

以上就是《使用Golang从PostgreSQL函数中获取多个值,其中函数返回整数并接受字符串数组》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>