dpwdldgn43486 2018-05-07 03:15
浏览 92
已采纳

DB.Exec args总是导致我的占位符错误

I have an SQL script with a variable I want to set from Golang.

SET @foo_bar_invitation_id = ?;
SELECT @foo_bar_invitation_id;

I.e. I want to set ? to "foobar". My code:

package main

import (
        "io/ioutil"
        "log"

        "database/sql"

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

type handler struct{ db *sql.DB }

func (h handler) runsql() (err error) {
        sqlscript, err := ioutil.ReadFile("script.sql")
        if err != nil {
                return
        }
        _, err = h.db.Exec(string(sqlscript), "foobar")
        if err != nil {
                log.Println(err)
        }
        return
}

Always results in Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @foo_bar_invitation_id' at line 2

I test via code generated by gotests:

import (
        "database/sql"
        "os"
        "testing"

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

var db *sql.DB

func TestMain(m *testing.M) {
        db, _ = sql.Open("mysql", os.Getenv("DSN"))
        defer db.Close()
        os.Exit(m.Run())
}

func Test_handler_runsql(t *testing.T) {
        type fields struct {
                db *sql.DB
        }
        tests := []struct {
                name    string
                fields  fields
                wantErr bool
        }{{
                "Check ID can be set",
                fields{db: db},
                false,
        }}
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
                        h := handler{
                                db: tt.fields.db,
                        }
                        if err := h.runsql(); (err != nil) != tt.wantErr {
                                t.Errorf("handler.step2runsql() error = %v, wantErr %v", err, tt.wantErr)
                        }
                })
        }
}

My DSN connection string includes ?multiStatements=true&sql_mode=TRADITIONAL.

I'm hoping I just do not understand how DB.Exec args interpolation / placeholder works, but I am finding it difficult to find examples.

  • 写回答

1条回答 默认 最新

  • dsz1966 2018-05-07 03:15
    关注

    The answer was to set interpolate params to true. https://github.com/go-sql-driver/mysql#interpolateparams

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题