如何将 SQL 参数与 NpgsqlDataAdapter 一起使用?

use*_*293 1 sql parameters npgsql

是否可以将参数与 NpgsqlDataAdapter 一起使用,就像我可以使用 NpgsqlCommand 一样:

          string sql = "SELECT * FROM tbl_student WHERE name = @val";
          NpgsqlCommand command = new NpgsqlCommand(sql, conn); 
          command.Parameters.AddWithValue("@val", name);
Run Code Online (Sandbox Code Playgroud)

我有这段代码,它显示有关学生的信息 ia 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();
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以以某种方式使用参数(如上例所示)而不是在 SQL 中使用 '" + name + "' 吗?我已经学会了总是使用参数,使用NpgsqlDataAdapter时也有必要吗?

谢谢。

Du *_*ran 5

我曾经有过同样的问题,这就是我想到的:

    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;
Run Code Online (Sandbox Code Playgroud)

你可以读一下这个这个