开发者

Error using prepared statements in C#

开发者 https://www.devze.com 2023-02-06 09:59 出处:网络
The parameters aren\'t add to the sql string, what i\'m doing wrong? SqlCommand comando = conexao.CreateCommand();

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

精彩评论

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