我试着用这个方法添加值来列出;
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列
这很正常?
发布于 2022-04-28 13:02:39
连接到数据库的方式不太合适,请始终使用“使用”。这样,一切都会自动关闭。
另外,只试着从您真正需要的sql服务器中获取所需的东西。我做了一个例子(也进行了测试):
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连接来说,这并不少见。
https://stackoverflow.com/questions/72036165
复制相似问题