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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分