开发者

Error using prepared statements in C#

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.ConsultaCom开发者_开发技巧ando(cmdSql, sqlParameters);


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


Assign CommandText before adding parameters and show cmdSql content.


On the AddWithValue method you are trying to pass an enum as the parameter value.

Replace this:

sqlParameters.AddWithValue("@quantidade", SqlDbType.Int).Value = quantidade;

With this:

sqlParameters.AddWithValue("@quantidade", quantidade);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜