C#操作Access数据库之SELECT操作是如何的呢,让我们开始讲解:
下面是我的自己在写测试程序的时候用到了,先列出来看看OleDbDataReader和OleDbDataAdapter是如何操作从数据库中选择记录的:
//通过ID得到当前留言详细内容.通过STRING类型参数
public Notebook getNoteFromID(string noteid)
{
Notebook tempnote=new Notebook(); //定义返回值
try //C#操作Access数据库之SELECT操作
{
OleDbConnection conn = getConn();
//getConn():得到连接对象
string strCom = "Select * from notes where id=" + noteid ;
OleDbCommand myCommand =new OleDbCommand(strCom,conn);
conn.Open();
OleDbDataReader reader;
reader =myCommand.ExecuteReader() ;
//执行command并得到相应的DataReader
//下面把得到的值赋给tempnote对象
if(reader.Read())
{ //C#操作Access数据库之SELECT操作
tempnote.id=(int)reader["id"];
tempnote.title=reader["title"].ToString();
tempnote.content=reader["content"].ToString();
tempnote.author=reader["author"].ToString();
tempnote.email=reader["email"].ToString();
tempnote.http=reader["http"].ToString();
tempnote.pic=reader["pic"].ToString();
tempnote.hits=(int)reader["hits"];
tempnote.posttime=(DateTime)reader["posttime"];
}
else //如没有该记录,则抛出一个错误!
{
throw(new Exception("当前没有该记录!"));
}
reader.Close();
conn.Close();
}
catch(Exception e)
{
//throw(new Exception("数据库出错:" + e.Message)) ;
}
return(tempnote); //返回Databook对象
} //C#操作Access数据库之SELECT操作上面的程序就是通过OleDbDataReader来得到特定的记录的!其中用到的语句我单独写到下面:
OleDbConnection conn = getConn(); //getConn():得到连接对象 string strCom = "Select * from notes where id=" + noteid ; //SQL语句 OleDbCommand myCommand =new OleDbCommand(strCom,conn); //建立OleDbCommand对象 conn.Open(); //注意我在前面说的Open语句在这里使用到了! OleDbDataReader reader; reader =myCommand.ExecuteReader() ; //执行command并得到相应的结果
我在每句话后都加入了说明,其中OleDbConnection conn = getConn();就是通过我前面提到的getConn函数来得到数据库连接的,其他语句没有什么好说的,都很简单,就不多说了!
C#操作Access数据库之SELECT操作:再列一个通过OleDbDataAdapter来得到记录的例程:
//Getlist():得到当前需要的留言列表
public DataView getNoteList()
{
DataView dataview;
System.Data.DataSet mydataset; //定义DataSet
try
{
OleDbConnection conn = getConn(); //getConn():得到连接对象
OleDbDataAdapter adapter = new OleDbDataAdapter();
string sqlstr="select * from notes order by posttime desc";
mydataset= new System.Data.DataSet();
adapter.SelectCommand = new OleDbCommand(sqlstr, conn);
adapter.Fill(mydataset,"notes");
conn.Close();
} //C#操作Access数据库之SELECT操作
catch(Exception e)
{
throw(new Exception("数据库出错:" + e.Message)) ;
}
dataview = new DataView(mydataset.Tables["notes"]);
return(dataview);
} 这个程序或许有些复杂,同样的,我还是先把那些关键语句列出,并说明:
OleDbConnection conn = getConn(); //通过函数getConn()得到连接对象 OleDbDataAdapter adapter = new OleDbDataAdapter(); //实例化OleDbDataAdapter对象 string sqlstr="select * from notes order by posttime desc"; //SQL语句 //C#操作Access数据库之SELECT操作 mydataset= new System.Data.DataSet(); //由于OleDbDataAdapter需要和DataSet结合使用,所以在这里定义了DataSet对象, //其实说OleDbDataAdapter复杂, //其实就是因为DataSet的缘故DataSet有些类似于ADO中的recordset 对象, //但功能远远超过了它,而且它和数据库是断开的,并能存放多个记录集! adapter.SelectCommand = new OleDbCommand(sqlstr, conn); //设置命令为SelectCommand类型的 adapter.Fill(mydataset,"notes"); //执行,并将结果添加到mydataset中的”notes”表中 conn.Close(); //关闭连接!