sql statement.exec错误:mssql:'?'附近的语法不正确 [英] sql statement.exec error: mssql: Incorrect syntax near '?'

查看:76
本文介绍了sql statement.exec错误:mssql:'?'附近的语法不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来了解此错误.该代码适用于sqlite. ?看起来sql包甚至没有在其中放置值,而是按原样发送问号. 我可以运行其他选择语句而不会出现问题,因此它不是连接问题或类似问题.

I need help understanding this error. The code works with sqlite. The ? looks like the sql package is not even putting a value there but sending the question mark as is. I can run other select statements without issues so its not a connection problem or something like that.

错误:'?'附近的语法不正确

func TestSQLServerInsert(t *testing.T) {
    db, err := sql.Open("sqlserver", "my_trusted_string")
    //db, err := sql.Open("sqlite3", "../data/utm_info.db")

    if err != nil {
        t.Errorf("could not open database: %v", err)
    }
    defer db.Close()

    c := controller.NewC(db)
    u := controller.UtilizationResponse{
        Snapshot: []int{46, 22, 4, 4, 5, 3, 0, 8, 49},
        History:  []float32{55.1, 47.2, 0.3, 33.4, 23.5},
        Time:     time.Now(),
    }

    affectedRows, err := c.InsertUtil(u)
    if err != nil {
        t.Errorf("could not insert into db: %v", err)
    }
    var count int64 = 1
    assert.Equal(t, affectedRows, count)
}

// InsertUtil response inserts a new record into the database
func (c *Controller) InsertUtil(u UtilizationResponse) (rowsAffected int64, err error) {
    return insertUtil(c.DB, u)
}

func insertUtil(db *sql.DB, u UtilizationResponse) (int64, error) {
    stmt, err := db.Prepare("INSERT INTO Utilization VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
    if err != nil {
        return 0, err
    }
    res, err := stmt.Exec(
        u.Time,
        u.Snapshot[0],
        u.Snapshot[1],
        u.Snapshot[2],
        u.Snapshot[3],
        u.Snapshot[4],
        u.Snapshot[5],
        u.Snapshot[6],
        u.Snapshot[7],
        u.Snapshot[8],
        u.History[0],
        u.History[1],
        u.History[2],
        u.History[3],
        u.History[4],
    )
    if err != nil {
        return 0, err
    }
    rowCnt, err := res.RowsAffected()
    if err != nil {
        return 0, err
    }
    return rowCnt, nil
}

type UtilizationResponse struct {
    Snapshot []int     `json:"snapshot,omitempty"`
    History  []float32 `json:"history,omitempty"`
    Time     time.Time `json:"time,omitempty"`
}

推荐答案

sqlserver驱动程序使用常规的MS SQL Server语法,并且期望sql中的参数查询形式为@Name或@ p1到@pN(常规位置).

The sqlserver driver uses normal MS SQL Server syntax and expects parameters in the sql query to be in the form of either @Name or @p1 to @pN (ordinal position).

insertSql := "insert into test (id, idstr) values (@p1, @p2)"

经过一些测试,我可以确认它是否有效.它甚至可以与sqlite3一起使用,因此这似乎是一种更为广泛接受的方式.

这篇关于sql statement.exec错误:mssql:'?'附近的语法不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆