How to use SQL parameters with NpgsqlDataAdapter?

别等时光非礼了梦想. 提交于 2019-12-20 06:46:53

问题


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.


回答1:


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;

You could read this and this.



来源:https://stackoverflow.com/questions/23413359/how-to-use-sql-parameters-with-npgsqldataadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!