C#操作Access数据库的例子

本文介绍如何使用ADO.NET进行数据库插入操作及SELECT查询,对比OleDbDataAdapter与OleDbDataReader的不同应用场景。
None.gif添加:   
None.gif  
using   System;   
None.gif  
using   System.Data;         
None.gif  
using   System.Data.OleDb;         
None.gif  
namespace   ADONETWriteQuery       
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif{     
ExpandedSubBlockStart.gifContractedSubBlock.gif              
/**////   <summary>     
InBlock.gif              
///   Summary   description   for   Class1.     
ExpandedSubBlockEnd.gif              
///   </summary>     

InBlock.gif              class   Class1     
ExpandedSubBlockStart.gifContractedSubBlock.gif              
dot.gif{       
InBlock.gif                          
static   void   Main(string[]   args)       
ExpandedSubBlockStart.gifContractedSubBlock.gif                          
dot.gif{       
InBlock.gif                                      
string   strDSN   =   "Provider=Microsoft.Jet.OLEDB.4.0;Data   
InBlock.gif
  Source=c:\\mcTest.MDB";       
InBlock.gif
                                      string   strSQL   =   "INSERT   INTO   Developer(Name,   Address   )   VALUES(   
InBlock.gif
  'NewName',   'NewAddress')"   ;       
InBlock.gif
                                          
InBlock.gif                                      
//   create   Objects   of   ADOConnection   and   ADOCommand         
InBlock.gif
                                      OleDbConnection   myConn   =   new   OleDbConnection(strDSN);       
InBlock.gif                                      OleDbCommand   myCmd   
=   new   OleDbCommand(   strSQL,   myConn   );       
InBlock.gif                                      
try       
ExpandedSubBlockStart.gifContractedSubBlock.gif                                      
dot.gif{       
InBlock.gif                                                  myConn.Open();       
InBlock.gif                                                  myCmd.ExecuteNonQuery();       
ExpandedSubBlockEnd.gif                                      }
       
InBlock.gif                                      
catch   (Exception   e)       
ExpandedSubBlockStart.gifContractedSubBlock.gif                                      
dot.gif{       
InBlock.gif                                                  Console.WriteLine(
"Oooops.   I   did   it   again:\n{0}",   e.Message);       
ExpandedSubBlockEnd.gif                                      }
       
InBlock.gif                                      
finally       
ExpandedSubBlockStart.gifContractedSubBlock.gif                                      
dot.gif{       
InBlock.gif                                                  myConn.Close();       
ExpandedSubBlockEnd.gif                                      }
       
InBlock.gif          
InBlock.gif          
InBlock.gif          
ExpandedSubBlockEnd.gif                          }
     
ExpandedSubBlockEnd.gif              }
       
ExpandedBlockEnd.gif  }
       
None.gif
在具体讲操作前,我认为有必要先认识一下下面的两个类:
System.Data.OleDb.OleDbDataAdapter
System.Data.OleDb.OleDbDataReader

System.Data.OleDb.OleDbDataAdapter:可以直接和DataSet联系,并操作数据源的,它的功能相对强大一些,因此也比较耗系统资源!
System.Data.OleDb.OleDbDataReader:则有些类似于ADO中的哪个只读向前的记录集,它最常用在只需要依次读取并显示数据的时候,相比System.Data.OleDb.OleDbDataAdapter来说,他耗用的系统资源要小!其实,OleDbDataReader能实现的功能,OleDbDataAdapter都可以实现,不过从资源使用率的角度考虑我们应该尽量使用前者!但有些功能,却是必须使用OleDbDataAdapter才可以实现的!


* SELECT操作!
下面是我的自己在写测试程序的时候用到了,先列出来看看OleDbDataReader和OleDbDataAdapter是如何操作从数据库中选择记录的:

//通过ID得到当前留言详细内容.通过STRING类型参数
public Notebook getNoteFromID(string noteid)
{
Notebook tempnote=new Notebook(); //定义返回值

try
{
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())
{
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对象
}

上面的程序就是通过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函数来得到数据库连接的,其他语句没有什么好说的,都很简单,就不多说了!


我再列一个通过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();
}
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语句

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(); //关闭连接!

在对上面的程序加一些补充说明,由于getNoteLista是得到一系列记录,并通过控件DataGrid来做分页显示的,所以我返回的是一个DataView类型的对象!

转载于:https://www.cnblogs.com/whitetiger/archive/2007/03/27/689367.html

本文介绍C#访问操作Access数据库的基础知识,并提供一个相关的例程。 1.通过ADO.NET的OleDb相关类来操作Access 主要知识点如下: using System.Data.OleDb; using System.Data; 连接字符串:String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=product.mdb"; 建立连接:OleDbConnection connection = new OleDbConnection(connectionString); 使用OleDbCommand类来执行Sql语句: OleDbCommand cmd = new OleDbCommand(sql, connection); connection.Open(); cmd.ExecuteNonQuery(); 2.取得Access自增标识字段在插入数据后的id值 cmd.CommandText = @"select @@identity"; int value = Int32.Parse(cmd.ExecuteScalar().ToString()); return value; 3.执行事务 需要用到OleDbTransaction,关键语句如下: OleDbConnection connection = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(); OleDbTransaction transaction = null; cmd.Connection = connection; connection.Open(); transaction = connection.BeginTransaction(); cmd.Transaction = transaction; cmd.CommandText=sql1; cmd.ExecuteNonQuery(); cmd.CommandText=sql2; cmd.ExecuteNonQuery(); transaction.Commit(); 4.执行查询,返回DataSet OleDbConnection connection = new OleDbConnection(connectionString); DataSet ds = new DataSet(); connection.Open(); OleDbDataAdapter da = new OleDbDataAdapter(sql, connection); da.Fill(ds,"ds"); 5.分页查询 分页查询使用OleDbDataReader来读取数据,并将结果写到一个DataSet中返回。 以上内容封装为三个可重用的类:AccessDBUtil,AccessPageUtil,Page 代码这里下载AccessDBUtilDemo.rar (191.37 KB , 下载:999次) 本例程是一个c#的winform程序,但是数据访问类可以在Web环境下使用。 本例程演示了: 1.Access数据库的插入,更新,修改,查询; 2.带参数的sql语句的使用,而不是拼SQL; 3.使用DataReader的分页查询,而不是用嵌套的SQL语句来分页; 4.用事务同时执行多个SQL语句; 5.在插入数据的同时返回最新的ID值; 6.整型,实型,字符串,日期型,布尔型五种数据类型的操作; 7.使用正则表达式来验证整数和实数; 8.listview用来显示数据的一些基本用法。 本示例不包括: 1.高效的分页查询,仅仅是提供了一种分页的方法,但我认为DataReader应该比嵌套的SQL语句快(未测试)。 2.完善的分页封装,只提供了分页的简单包装。 3.嵌套的事务处理,提供了同时执行多个sql语句的事务处理,但不支持嵌套事务。 4.listview的使用,只是利用winform控件来演示数据访问,因此不能作为winform编程的良好示例,例如添加数据时界面并没有很好地更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值