首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Datareader将列出

Datareader将列出
EN

Stack Overflow用户
提问于 2022-04-27 23:00:51
回答 1查看 322关注 0票数 1

我试着用这个方法添加值来列出;

代码语言:javascript
复制
    public List<Product> GetAll()
    {
        SqlCommand command = new SqlCommand("Select * from products",Connection.connection);
        Connection.connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        List<Product> products = new List<Product>();
   
        while (reader.Read())
        {
            Product product = new Product
            {
                ProductId = Convert.ToInt32(reader["ProductId"]),
                StockCode = reader["StockCode"].ToString(),
                Barcode = reader["Barcode"].ToString(),
                ProductName = reader["ProductName"].ToString()             
            };
            products.Add(product);
        }
            
            reader.Close();
            if (command.Connection.State==ConnectionState.Open)
            {
                command.Connection.Close();
            }   
        return products;
      
    }

我只想要这个产品表中的4列

但是像这样的专栏

这很正常?

EN

回答 1

Stack Overflow用户

发布于 2022-04-28 13:02:39

连接到数据库的方式不太合适,请始终使用“使用”。这样,一切都会自动关闭。

另外,只试着从您真正需要的sql服务器中获取所需的东西。我做了一个例子(也进行了测试):

代码语言:javascript
复制
public List<Product> GetAll()
    {
        string command = "SELECT ProductId, StockCode, Barcode, ProductName FROM products";
        List<Product> products = new List<Product>();

        Connection.Open();
        using (SqlCommand cmd = new SqlCommand(command, Connection))
        {
            using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    products.Add(
                        new Product {
                            ProductId = Convert.ToInt32(reader["ProductId"]),
                            StockCode = reader["StockCode"].ToString(),
                            Barcode = reader["Barcode"].ToString(),
                            ProductName = reader["ProductName"].ToString()
                        }
                    );
                }
            }
        }

        return products;
    }

结果

如果调用该函数,则将其放入try catch块将是有意义的,因为对于有问题的sql连接来说,这并不少见。

参考:我可怕的mssql我的产品课

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72036165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档