当前位置:首页>网络学院>程序开发>c#教程>文章内容

在VisualC#中访问不同数据库(3)

[ 来源:www.it55.com | 作者: | 时间:2007-07-14 | 收藏 | 推荐 ] 【

     (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

返回顶部
 

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]

图片文章