Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql statement.exec error: mssql: Incorrect syntax near '?'

Tags:

sql-server

go

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.

Error: Incorrect syntax near '?'

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"`
}
like image 365
The Fool Avatar asked Aug 06 '26 08:08

The Fool


1 Answers

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)"

After some testing, I can confirm it works. It even works with sqlite3 so this seems to be a more widely accepted way.

like image 94
The Fool Avatar answered Aug 08 '26 09:08

The Fool