Search code examples
c#postgresqlnpgsql

Work with double quotes and parameter adding to a query


Original Query which I can run positive in PgAdminIII:

SELECT * FROM oestrat."Themenfeld"

oestrat and Themenfeld are strings coming from Winform textboxes.

So my query in VS would be:

string qry = "SELECT * FROM @schema.\"@line\"";

NpgsqlCommand cmd = conn.CreateCommand();
cmd.Parameters.Add(new NpgsqlParameter("@schema", tbSchema.Text)); // tbSchema.Text = oestrat
cmd.Parameters.Add(new NpgsqlParameter("@line", l)); // string l = Themenfeld

cmd.CommandText = qry;

conn.Open();
NpgsqlDataReader dr = cmd.ExecuteReader();

while (dr.Read()) <<< ERROR
{
     ....
}

It always catches an Exception:

42601: syntax error at or near "@"

Solution

  • I don't believe you can specify table names as parameters... only values can be specified as parameters.

    Instead, either have a white-list of permitted table names, or at least a white-list of permitted characters within table names, apply that to your user input, and then - carefully - build the SQL dynamically.