Reputation: 813
Is it possible to use parameters together with NpgsqlDataAdapter, as I can do with NpgsqlCommand:
string sql = "SELECT * FROM tbl_student WHERE name = @val";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("@val", name);
I have this code, which displays the information about the students i a gridview:
string sql = "SELECT * FROM tbl_student WHERE studentname = '" + name + "'";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds); // filling DataSet with result from NpgsqlDataAdapter
dt = ds.Tables[0]; // select select first column
GridView1.DataSource = dt; //connect grid to DataTable
GridView1.DataBind();
My question is: can I somehow use parameters (as in the example above) instead of using '" + name + "' in the SQL? I have learned always to use parameters, is it also necessary when using NpgsqlDataAdapter?
Thank you.
Upvotes: 1
Views: 8337
Reputation: 537
I used to have the same question and this is what I came up with:
string sql = "SELECT * FROM tbl_student WHERE studentname = @param";
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
command.Parameters.Add("@param", textBox_studentname.Text); //add the parameter into the sql command
DataTable dt = new DataTable();
//load the DataReader object of the command to the DataTable
dt.Load(NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection));
GridView1.DataSource = dt;
Upvotes: 5