/**////
/// 给定一个文章编号, 读取数据库中的一篇文章
/// ///
articlepublic article getarticle(int articleid)
{
string sql = "select * from " + _articledb + "where id='" + articleid + "'";
sqlcommand cmd = new sqlcommand(sql,_conn);
sqldatareader dr = cmd.executereader();
article article = populatearticle(dr);
dr.close();
return article;
}
/**////
/// 更新数据库记录,注意需要设定文章的编号
/// ///
public void updatearticle(article article)
{
string sql = "update " + _articledb +" set [email protected],[email protected],[email protected],[email protected]"
+ " where id = @articleid";
sqlcommand cmd = new sqlcommand(sql,_conn);
cmd.parameters.add("@articleid",sqldbtype.int,4).value = article.id;
cmd.parameters.add("@topic",sqldbtype.nvarchar,100).value = article.topic;
cmd.parameters.add("@author",sqldbtype.nvarchar,100).value = article.author;
cmd.parameters.add("@content",sqldbtype.ntext).value = article.content;
cmd.parameters.add("@posttime",sqldbtype.datetime).value = article.posttime;
cmd.executenonquery();
}
/**////
/// 取出数据库中特定作者发表的文章
/// ///
///
articlecollectionpublic articlecollection getarticlesbyauthor(string author)
{
string sql = "select * from " + _articledb +" where author='" + author + "'";
sqlcommand cmd = new sqlcommand(sql, _conn);
articlecollection articlecollection = new articlecollection();
sqldatareader dr = cmd.executereader();
while (dr.read())
{
article a = populatearticle(dr);
articlecollection.add(a);
}
dr.close();
return articlecollection;
}
/**////
/// 删除给定编号的一篇文章
/// ///
public void deletearticle(int articleid)
{
string sql = "delete from " + _articledb + " where id='" + articleid + "'";
sqlcommand cmd = new sqlcommand(sql, _conn);
cmd.executenonquery();
}
/**////
/// 通过 sqldatareader 生成文章对象
/// ///
///
private article populatearticle(sqldatareader dr)
{
article art = new article();
art.id = convert.toint32(dr["id"]);
art.author = convert.tostring(dr["author"]);
art.topic = convert.tostring(dr["topic"]);
art.content = convert.tostring(dr["content"]);
art.posttime= convert.todatetime(dr["posttime"]);
return art;
}
/**////
/// 增加一篇文章到数据库中,返回文章的编号
/// ///
///
刚刚插入的文章的编号public int addpost(article article)
{
string sql = "insert into " + _articledb +"(author,topic,content,posttime)"+
"values(@author, @topic, @content, @posttime) "+
"select @postid = identity";
sqlcommand cmd = new sqlcommand(sql,_conn);
cmd.parameters.add("@postid",sqldbtype.int,4);
cmd.parameters["@postid"].direction = parameterdirection.output;
cmd.parameters.add("@author",sqldbtype.nvarchar,100).value = article.author;
cmd.parameters.add("@topic",sqldbtype.nvarchar,400).value = article.topic;
cmd.parameters.add("@content",sqldbtype.text).value = article.content;
cmd.parameters.add("@posttime",sqldbtype.datetime).value = article.posttime;
cmd.executenonquery();
article.id = (int)cmd.parameters["@postid"].value;
return article.id;
}
}
}