答案 0 :(得分:0)
如果你想填充一个DataTable
(绝对不需要使用DataSet
,如果你只获得一个表,没有关系) - 那就用这个代码:
public ActionResult notCk_Pk(String FirstName, String LastName, int? Salary, String Gender)
{
List<Counting> l = new List<Counting>();
string query = "select * from tblEm where FirstName = @FirstName";
string ConnectionString = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
-- set up and connection and command in "using"
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
-- define parameter - don't use "AddWithValue"
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = FirstName;
-- define data adapter and use the *existing* "cmd"
SqlDataAdapter da = new SqlDataAdapter(cmd);
-- fill a DataTable since you only get data from a single table
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
l.Add(new Counting() { FirstNamecount = Convert.ToInt32(dr[0]),
LastNamecount = Convert.ToInt32(dr[1]),
Salary = Convert.ToInt32(dr[2]),
Gendercount = Convert.ToInt32(dr[3])
});
}
}
var todoListsResults = l.Select(
a => new
{
a.FirstNamecount,
a.LastNamecount,
a.Salary,
a.Gendercount
});
var jsonData = new
{
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
我已经改进了点:
ConnectionString
,如果你获取它 - 不要从config获取连接字符串,然后使用硬编码的字符串...... .ExecuteNonQuery()
或.ExecuteScalar()
来电SqlDataAdapter
创建SqlCommand cmd
以使用该命令已设置的连接和参数!.Add()
来电定义参数 - 不 .AddWithValues()
(请参阅本文Can we stop using AddWithValue() already?了解原因 - 它会导致意想不到的惊人结果......)