manuzi1 manuzi1 - 1 year ago 116
C# Question

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;

NpgsqlDataReader dr = cmd.ExecuteReader();

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

It always catches an Exception:

42601: syntax error at or near "@"

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download