在 C# 中使用准备好的语句时出错
参数没有添加到sql字符串中,我做错了什么?
SqlCommand comando = conexao.CreateCommand();
comando.CommandTimeout = 7200;
foreach (SqlParameter parametro in parametros)
{
comando.Parameters.Add(new SqlParameter(parametro.ParameterName, parametro.Value));
}
comando.CommandText = cmdSql;
comando.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = comando;
try
{
adapter.Fill(dt);
}
catch (Exception ex) { Console.Write(ex.Message); }
conexao.Close();
return dt;
Sql 字符串,以及调用上面方法的方法。
string cmdSql = "select top @quantidade * from representante";
SqlParameterCollection sqlParameters = new SqlCommand().Parameters;
sqlParameters.AddWithValue("@quantidade", SqlDbType.Int).Value = quantidade;
return Persistencia.Persistencia.ConsultaComando(cmdSql, sqlParameters);
The parameters aren't add to the sql string, what i'm doing wrong?
SqlCommand comando = conexao.CreateCommand();
comando.CommandTimeout = 7200;
foreach (SqlParameter parametro in parametros)
{
comando.Parameters.Add(new SqlParameter(parametro.ParameterName, parametro.Value));
}
comando.CommandText = cmdSql;
comando.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = comando;
try
{
adapter.Fill(dt);
}
catch (Exception ex) { Console.Write(ex.Message); }
conexao.Close();
return dt;
The Sql String, with the method who call the method above.
string cmdSql = "select top @quantidade * from representante";
SqlParameterCollection sqlParameters = new SqlCommand().Parameters;
sqlParameters.AddWithValue("@quantidade", SqlDbType.Int).Value = quantidade;
return Persistencia.Persistencia.ConsultaComando(cmdSql, sqlParameters);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
感谢您的帮助,但解决方案是使用
string cmdSql = "select top (@quantidade) * fromrepresentante";
在 MSDN 中得到了回答:MSDN BRASIL 中的答案
Thanks for all helping but the solution is use
string cmdSql = "select top (@quantidade) * from representante";
was answered in the MSDN:Answer in MSDN BRASIL
在添加参数之前分配
CommandText
并显示cmdSql
内容。Assign
CommandText
before adding parameters and showcmdSql
content.在您正在尝试的 AddWithValue 方法上传递枚举作为参数值。
将其替换
为:
On the AddWithValue method you are trying to pass an enum as the parameter value.
Replace this:
With this: