简体   繁体   中英

panic: sql: expected 0 arguments, got 1

I am trying to execute queries with Go, but I cannot manage to request any query, because it keeps giving me the same error over and over.

I have changed the query multiple times, but that doesn't seem to help. Also i have changed QueryRow in Query, unfortunately that doesn't help either.

func test123() {

    db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/vitaintellectdb")
    if err != nil {
        panic(err.Error())
    }

    id := 1
    var col string
    sqlStatement := `SELECT naam FROM medewerker WHERE naam="jansen"`
    row := db.QueryRow(sqlStatement, id)
    err2 := row.Scan(&col)
    if err2 != nil {
        if err2 == sql.ErrNoRows {
            fmt.Println("Zero rows found")
        } else {
            panic(err2)
        }
    }

}

QueryRow is designed to give you 1 row in return. Unfortunately the error is telling me that there should be no returns, I expect 1 row in return.

The error is telling you that you are passing an argument to QueryRow that it is not expecting.

Your SQL statement doesn't have any placeholders so isn't expecting any but you are giving it one of id . Just change:

row := db.QueryRow(sqlStatement, id)

to:

row := db.QueryRow(sqlStatement)

sqlStatement := `SELECT naam FROM medewerker WHERE naam="jansen"`
row := db.QueryRow(sqlStatement, id)

The given sql statement has no parameter. The following sql statement including the placeholder might work better.

sqlStatement := `SELECT naam FROM medewerker WHERE medewerkernummer =?`
row := db.QueryRow(sqlStatement, id)

Depending how your id -column is named you might have to change naam=? to idColumn=? . In the examples here you might find inspiration.

You can use fmt.Sprintf to do this really cleanly in one line.

...
    row := db.QueryRow(fmt.Sprintf("SELECT naam FROM medewerker WHERE naam='%s', id)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM