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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图