我有一个包含3列的表(EmpId,EmpName,EmpSalary)。 我正在使用预准备语句使用预准备语句从该表中检索所有数据。 这是我写的......
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "@id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "@name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "@sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while(dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
但是我收到如下错误: “参数化的Query需要参数@id,它没有提供。”
我在这里做错了什么.. ??
答案 0 :(得分:1)
请使用cmd.Parameters.AddWithValue()
。不推荐使用cmd.Parameters.Add()
。谷歌的用途: - )
答案 1 :(得分:0)
我检查了你的代码,你需要提供如下的参数值。
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails ";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "@id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "@name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "@sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
//i assume you forgot to setup parameter values.
paraId.Value = 1;
paraName.Value = "thisName";
paraSal.Value = 343;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while (dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}