(6).在程序中,还设计了一个例外处理。在出现例外的时候,显示错误信息。错误信息的捕获是通过System.Data.OleDb名称空间中的类--OleDbException来实现的。具体如下:
try
{
…….
![]() | ![]() | ![]() | ![]() |
}
catch ( OleDbException e )
{
Console.WriteLine ( "错误类型:", e.Errors[0].Message ) ;
}
first.cs 的程序源代码如下:
using System ;
using System.Data.OleDb ;
using System.Windows.Forms ;
// 导入程序中用的的所有名称空间
class OleDbTest {
public static void Main ( )
{
string strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
it55.com Application.StartupPath + "\\my.mdb" ;
OleDbConnection aConnection = new OleDbConnection ( strConnect ) ;
// 建立指向
数据库的连接
OleDbCommand aCommand = new OleDbCommand ( "select * from Persons" ,
aConnection ) ;
// 设计所需要返回的
数据集的内容
try {
aConnection.Open ( ) ;
// 打开指向
数据库连接
OleDbDataReader aReader = aCommand.ExecuteReader ( ) ;
// 返回需要的
数据集内容
Console.WriteLine ( "以下就是打开后的
数据集的一个字段的所有内容!" ) ;
vd;k;l www.it55.com rdfg
while ( aReader.Read ( ) ) {
Console.WriteLine ( aReader.GetString (0) ) ;
}
// 屏幕输出
数据集的第一个字段的所有内容,如果要第二个字段把"0"改为"1"
aReader.Close ( ) ;
// 关闭
数据集
aConnection.Close ( ) ;
// 关闭指向
数据库的连接
}
catch ( OleDbException e )
{
Console.WriteLine ( "错误类型:", e.Errors[0].Message ) ;
// 如果出错,输出错误信息
}
}
}
(编辑:IT资讯之家 www.it55.com)