Reputation:
I am using the following query to query the DB. But I get the error sql: expected 0 arguments, got 1
.
Following is the code that I am using:
row := DB.QueryRow(`SELECT COUNT(*) FROM Users WHERE Id = "%s";`, userID)
if err != nil {
return err.Error()
}
I am using the following package and driver
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
Edit:
I also tried with the following query, but I get the same error.
row := DB.QueryRow(`SELECT COUNT(*) FROM Users WHERE Id = "$1";`, userID)
if err != nil {
return err.Error()
}
Upvotes: 2
Views: 3717
Reputation: 445
The reason why your code isn't working is because you are using a formatted string syntax, but nothing to format it. And the reason why no arguments were expected were probably because the correct placeholders weren't used. Try wrapping up the query in a formatter like fmt.Sprintf
like:
query := fmt.Sprintf(`SELECT COUNT(*) FROM Users WHERE Id = '%s'`, userID)
row := DB.QueryRow(query)
if err != nil {
return err.Error()
}
You can also avoid fmt.Sprintf
. Instead you can follow a format more specific to the driver you are using. For example
// For "github.com/go-sql-driver/mysql"
row := DB.QueryRow("SELECT COUNT(*) FROM Users WHERE Id=?", userID)
// For "github.com/mattn/go-sqlite3"
row := DB.QueryRow("SELECT COUNT(*) FROM Users WHERE Id=?", userID)
// For "github.com/lib/pq"
row := DB.QueryRow("SELECT COUNT(*) FROM Users WHERE Id=$1", userID)
Upvotes: 1
Reputation:
As suggested in this thread, you basically need to use ?
as a placeholder in the Query
or QueryRow
functions. So, the query above should look like this:
row := DB.QueryRow(`SELECT COUNT(*) FROM Users WHERE Id = ? ;`, userID)
if err != nil {
return err.Error()
}
Upvotes: 2