在VisualC#中访问不同数据库(3)
在VisualC#中访问不同数据库(3)
作者: 马金虎 &;nbsp来自:网络
(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="
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 ( "以下就是打开后的数据集的一个字段的所有内容!" ) ;
while ( aReader.Read ( ) ) {
Console.WriteLine ( aReader.GetString (0) ) ;
}
// 屏幕输出数据集的第一个字段的所有内容,如果要第二个字段把"0"改为"1"
aReader.Close ( ) ;
// 关闭数据集
aConnection.Close ( ) ;
// 关闭指向数据库的连接
}
catch ( OleDbException e )
{
Console.WriteLine ( "错误类型:", e.Errors[0].Message ) ;
// 如果出错,输出错误信息
}
}
}
(2005-9-15:12:18)
| 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。 |