如何在NpgsqlDataAdapter中使用SQL参数? [英] How to use SQL parameters with NpgsqlDataAdapter?

查看:710
本文介绍了如何在NpgsqlDataAdapter中使用SQL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

我有这段代码,它在gridview中显示有关学生的信息:

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();

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

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?

谢谢.

推荐答案

我曾经有同样的问题,这是我想出的:

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;

您可以阅读 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆