简体   繁体   中英

Parameter SQL in C# doesn't work

I have this code and it does not work. Does anyone know why?

It did not return any data, but if run the query in SQL Server it returns the data.

using (SqlConnection connection = new SqlConnection(_dbContext.GetConnectionString()))
{
    using (SqlCommand command = new SqlCommand())
    {
        StringBuilder stringQuery = new StringBuilder();
        stringQuery.Append(" SELECT cd_material, ds_material");
        stringQuery.Append(" FROM tbl_materiais");
        stringQuery.Append(" WHERE ds_material like @Name");

        command.Parameters.AddWithValue("@Name", "%" + name + "%");
        command.CommandText = stringQuery.ToString();
        command.CommandType = System.Data.CommandType.Text;
        command.Connection = connection;

        connection.Open();

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                _product = new ProductSell();
                ((IProduct)_product).ID = reader.GetFieldValue<int>(0);
                ((IProduct)_product).Name = reader.GetFieldValue<string>(1);
                listProduct.ToList<IProduct>().Add(_product);
            }
        }
    }
} 

What is listProduct and why do you call its ToList<>() ?

listProduct.ToList<IProduct>() returns a new instance of List<IProduct> that is forgotten after this line executes. Calling .Add(_product) on this returned list does not affect listProduct .

My problem stay here

while (reader.Read())
        {
         DoSomething();
        }

reader.Read() never is read, my table is simple, have only attributes: cd_material(int), ds_material(varchar). And Exception not are triggered. This query :

SELECT cd_material, ds_material FROM tbl_materiais WHERE ds_material = '%produto%' 

Many rows are returned if in owner database ( sql management)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM