使用Ado.net的内部联接无法正常运行。请参阅附带的代码并告诉我。我在“值”中成功接收字符串数组值。我想我的代码本身有一些问题。
public JsonResult searchdata(String[] values,String[] values1,String[] values2)
{
//String str;
//for (int i = 0; i <= values.Length; i++)
//{
// str = values[i];
// Console.WriteLine(str);
//}
using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
{
DataSet ds = new DataSet();
connection.Open();
SqlCommand cmd = connection.CreateCommand();
String str= "select accntname,BU,salesop,isdormant from fourth_page as fg"+
" INNER JOIN linked as ld on ld.productid=fg.productid"+
"INNER JOIN isdormant as it on it.productid=ld.productid"+
"where fg.accountname in" + values;
cmd.CommandText = str;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = cmd;
mySqlDataAdapter.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
Console.WriteLine(dr[0].ToString() + "" + dr[1].ToString() + "" + Convert.ToInt32(dr[2]) + "" + Convert.ToBoolean(dr[3]));
}
connection.Close();
}
return Json(values);
}
答案 0 :(得分:0)
values
是一个数组,您无法将其注入查询。您需要从数组中读取每个项目并在in子句中使用它。以下代码应该可以正常工作。
我还用SqlDataReader替换了SqlDataAdapter来查询数据。
public JsonResult searchdata(String[] values)
{
var result = new List<string>();
using (var con = new SqlConnection("Put your conn string here"))
{
using (var cmd = new SqlCommand())
{
var str= "select accntname,BU,salesop,isdormant from fourth_page as fg"+
" INNER JOIN linked as ld on ld.productid=fg.productid"+
" INNER JOIN isdormant as it on it.productid=ld.productid ";
if (values != null && values.Any())
{
var items = values.Select((x, counter) => "@v" + counter);
str +=string.Format(" where fg.accountname in ({0})",
string.Join(",", items));
var paramCounter = 0;
foreach (var value in values)
{
cmd.Parameters.AddWithValue("@v" + paramCounter, value);
paramCounter++;
}
}
cmd.CommandText = str;
cmd.Connection = con;
con.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var c1 = reader.GetString(reader.GetOrdinal("accntname"));
result.Add(c1);
}
}
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}