c# Using Parameters.AddWithValue in SqlDataAdapter

不羁的心 提交于 2019-12-17 05:05:18

问题


How can I use Parameters.AddWithValue with an SqlDataAdapter. Below searching codes.

var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);

I rewrote the code like this:

SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%@search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("@search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);

but it failed.


回答1:


The string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter.
You could add parameters to that command with this code

da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE @search",
                        _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("@search","%" + txtSearch.Text + "%");
  • First, remove the single quote around the parameter placeholder.
  • Second, add the wildcard character directly in the Value parameter of AddWithValue

You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.

  • First: Can we stop using AddWithValue() already? where the author discuss how AddWithValue could give back wrong results in your queries
  • Second: How Data Access Code Affects Database Performance where the author presents evidences of strong performance problems for AddWithValue

So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as

da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE @search",
                        _mssqlCon.connection);
da.SelectCommand.Parameters.Add(new SqlParameter
{
    ParameterName = "@search",
    Value = "%" + txtSearch.Text + "%",
    SqlDbType = SqlDbType.NVarChar,
    Size = 2000  // Assuming a 2000 char size of the field annotation (-1 for MAX)
});



回答2:


Use da.SelectCommand.Parameters.Add() instead of cmd.Parameters.Add(), here's a sample for dealing with a stored procedure which takes two parameters and second one is a nullable int parameter:

public DataTable GetData(int par1, int? par2)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlDataAdapter da = new SqlDataAdapter())
        {
            string sql = "StoredProcedure_name";
            da.SelectCommand = new SqlCommand(sql, conn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@Par1", SqlDbType.Int).Value = par1;
            da.SelectCommand.Parameters.Add("@Par2", SqlDbType.Int).Value = (object)par2?? DBNull.Value;

            DataSet ds = new DataSet();
            da.Fill(ds, "SourceTable_Name");

            DataTable dt = ds.Tables["SourceTable_Name"];

            //foreach (DataRow row in dt.Rows)
            //{
            //You can even manipulate your data here
            //}
            return dt;
        }
    }
}



回答3:


Try this:

mySearchString = "Select * From test Where ([title] LIKE '%' + @title + '%')";
cmd.Parameters.Add("@title", SqlDbType.VarChar, 120);
cmd.Parameters("@title").Value = TextBox1.Text;



回答4:


I use Repeater for show data

int queryString =int.Parse(Request.QueryString["Id"]);

SqlConnection conn =new SqlConnection("server=.; Database=Northwind; 
Integrated Security=true;");

try{
conn.Open();

SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT ProductID, ProductName, UnitPrice, CategoryID FROM Products WHERE CategoryID =@CategoryID", conn);

dataAdapter.SelectCommand.Parameters.Add("@CategoryID", queryString);
                        DataSet dataSet = new DataSet();
                        dataAdapter.Fill(dataSet);
                        QueryStringProductListRepeater.DataSource = dataSet;
                        QueryStringProductListRepeater.DataBind();
}

catch{
Response.Write("QueryStringProductListRepeater");
}

finally{
conn.Close();
}


来源:https://stackoverflow.com/questions/13276602/c-sharp-using-parameters-addwithvalue-in-sqldataadapter

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