使用ADO.NET获取产品列表时遇System.FormatException异常求助
问题原因与解决办法
异常根源
你遇到的System.FormatException是因为数据库中部分字段的值为NULL或空字符串,而你直接用int.Parse()去解析这些空内容导致的。比如CartId、FactorId这类字段如果在数据库允许为NULL,或者存在空值记录,reader["字段名"].ToString()会得到空字符串,int.Parse无法解析空字符串,就会抛出这个异常。
另外,当数据库字段是DBNull时,reader["字段名"].ToString()也会返回空字符串,同样触发报错。
解决方法
方法1:使用int.TryParse安全解析
这种方式可以处理空字符串或无效整数的情况,给字段设置默认值(比如0):
public List<Product> GetAll() { using (SqlConnection sql = new SqlConnection(_connectionString)) { sql.Open(); SqlCommand command = sql.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "Select * from Products"; var reader = command.ExecuteReader(); List<Product> products = new List<Product>(); while (reader.Read()) { int cartId = 0; int factorId = 0; int.TryParse(reader["CartId"].ToString(), out cartId); int.TryParse(reader["FactorId"].ToString(), out factorId); products.Add(new Product { Id = int.Parse(reader["Id"].ToString()), Name = reader["Name"].ToString(), Brand = reader["Brand"].ToString(), Price = int.Parse(reader["Price"].ToString()), CartId = cartId, FactorId = factorId }); } reader.Close(); return products; } }
方法2:直接读取强类型值(更高效)
利用ADO.NET的GetInt32方法,结合IsDBNull判断字段是否为NULL,避免字符串转换的开销:
public List<Product> GetAll() { using (SqlConnection sql = new SqlConnection(_connectionString)) { sql.Open(); SqlCommand command = sql.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "Select * from Products"; var reader = command.ExecuteReader(); List<Product> products = new List<Product>(); while (reader.Read()) { products.Add(new Product { Id = reader.GetInt32(reader.GetOrdinal("Id")), Name = reader["Name"].ToString(), Brand = reader["Brand"].ToString(), Price = reader.GetInt32(reader.GetOrdinal("Price")), CartId = reader.IsDBNull(reader.GetOrdinal("CartId")) ? 0 : reader.GetInt32(reader.GetOrdinal("CartId")), FactorId = reader.IsDBNull(reader.GetOrdinal("FactorId")) ? 0 : reader.GetInt32(reader.GetOrdinal("FactorId")) }); } reader.Close(); return products; } }
额外检查
建议先检查Products表的数据,确认Price、CartId、FactorId这些字段是否存在非整数的内容或空值记录,必要时修正数据或者调整数据库字段的约束(比如设置默认值)。
内容的提问来源于stack exchange,提问作者Alireza Alavi
相关产品推荐
相关产品推荐

