[C#] C#访问数据库的代码(Access版本)
//导入程序中用的的所有名称空间
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 ( "以下就是打开后的数据集的一个字段的所有内容!" ) ;
//屏幕输出数据集的第一个字段的所有内容,如果要第二个字段把"0"改为"1"
while ( aReader.Read ( ) ) {
Console.WriteLine ( aReader.GetString (0) ) ;
}
//关闭数据集
aReader.Close ( ) ;
//关闭指向数据库的连接
aConnection.Close ( ) ;
}
catch ( OleDbException e )
{
//如果出错,输出错误信息
Console.WriteLine ( "错误类型:", e.Errors[0].Message ) ;
}
}
}
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 ( "以下就是打开后的数据集的一个字段的所有内容!" ) ;
//屏幕输出数据集的第一个字段的所有内容,如果要第二个字段把"0"改为"1"
while ( aReader.Read ( ) ) {
Console.WriteLine ( aReader.GetString (0) ) ;
}
//关闭数据集
aReader.Close ( ) ;
//关闭指向数据库的连接
aConnection.Close ( ) ;
}
catch ( OleDbException e )
{
//如果出错,输出错误信息
Console.WriteLine ( "错误类型:", e.Errors[0].Message ) ;
}
}
}