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"`
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With