1、业务实体:
public class Article
{
private int _articleId;
private string _title;
private string _articleDetails;
public int ArticleId
{
get { return _articleId; }
set { _articleId = value; }
}
…
}
2、调用通用的SQLHelper ,数据访问如下:
public static Article GetArticleByArticleId(int id)
{
string sql = "select * from article where articleId=@articleId";
try
{
using (SqlDataReader reader = SqlHelper.GetReader(sql, new SqlParameter("@articleId", id)))
{
if (reader.Read())
{ return FillRecord(reader); }
else
{ return null; }
}
}
catch (Exception e)
{
Console.WriteLine(e.Message); throw e;
}
}
3、业务逻辑
public static class ArticleManager
{
public static Article GetArticlesByArticleId(int id)
{
return ArticleService.GetArticleByArticleId(id);
}
}
程序运行显示 数据访问错误显示:
throw e处; 对象不能从 DBNull 转换为其他类型。请各位指示!
SqlDataReader reader = SqlHelper.GetReader(sql, new SqlParameter("@articleId", id)调试跟踪下,看看是什么问题
你自己定义的方法的具体内容贴出来啊!你添加断点,看看是SqlHelper.GetReader(sql, new SqlParameter("@articleId", id))的问题还是FillRecord(reader)的问题。
/// <summary>
/// 执行有参SQL语句,并返回SqlDataReader
/// </summary>
public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql, Connection);
cmd.Parameters.AddRange(values);
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
@WesternWind: 你查询的结果里是不是有空值啊?
@WesternWind: 还有FillRecord(reader); 这是什么方法啊?
@yanzhe:
/// 实º¦Ì体¬?对?象¨®填¬?充?业°¦Ì务?对?象¨®公?共2方¤?法¤¡§
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static Article FillRecord(SqlDataReader reader)
{
Article a = new Article();
a.ArticleId = Convert.ToInt32(reader["articleId"]);
a.ChannelId = Convert.ToInt32(reader["channelId"]);
a.Title = Convert.ToString(reader["title"]);
a.ArticleDetails = Convert.ToString(reader["articleDetails"]);
return a; }
}
}
@yanzhe:
数据库中部分字段应该是有 空值 滴吧1~!
@WesternWind: 是FillRecord()的问题。就是因为是空值,才会有这个错误,加个是否为空的判断呗