Search code examples
postgresqlgopgx

query is returning "expected 0 arguments, got 1"


I am trying to query a database that I know has data in it from directly querying within pgadmin. When I query using the following code it returns no results:

const DATABATE_URL = "postgres://postgres:pw@localhost:5432/postgresdb"


conn, err := pgx.Connect(context.Background(), DATABATE_URL)
    defer conn.Close(context.Background())

    if err != nil {
        fmt.Printf("Connection failed: %v\n", err)
        os.Exit(-1)
    }

    stmt := "SELECT * FROM nodes"
    rows, err := conn.Query(context.Background(), stmt, nil)
    if err != nil {
        fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) //error outs here "expected 0 arguments, got 1"
        os.Exit(1)
    }
    for rows.Next() {
        var results string
        err = rows.Scan(&results)
        if err != nil {
            fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n %n", err)
            os.Exit(1)
        }
        fmt.Println(results)
    }

When I directly connect to the database through goland and pgadmin and query with the same statement I can see all the data. What am I missing here?


Solution

  • The pgx Conn.Query accepts a context, statement and arguments:

    func (c *Conn) Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)
    

    You are passing it a context, statement and nil:

    rows, err := conn.Query(context.Background(), stmt, nil)
    

    So the nil is treated as an argument but your SQL statement does not contain any argument placeholders (e.g. SELECT * FROM nodes where id=$1) hence the error. To fix this run:

    rows, err := conn.Query(context.Background(), stmt)
    

    However it would also be worth editing your sql to specify the column you want (e.g. SELECT nodename FROM nodes).

    Note: When raising a question like this please include the error in the question body rather than just as a comment in the code (which is easy to miss).