C#连接ACCESS数据库代码实例
C# 连接ACCESS数据库代码实例
1. 建立一个access数据库名字为CSharptest.mdb,里面有一个表person,它有两个字段personname(备注:由于name是access的关键字之一,所以尽量不要将字段名或者表明起为name,否则可能出错)和age
2. 将access数据库文件CSharptest.mdb所在的目录
..(一定要
...目录下
...)(假设名
...在.www
为access)设为共享
.....),假设我的机器地址为192.168.232.135,那么设为共享后,..(一定要共享
在地址栏内输入//192.168.232.135/access/这个目录应该之后可以看到CSharptest.mdb文件。
3. 打开VS2008,菜单中点”新建”->“项目”->“Visual C#”->“Windows”->“windows 窗体应用程序”,建立一个新的C#窗体程序。
4. 修改代码文件program.cs的内容,其完整C#代码如下。
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication3
{
static class Program
{
///
///应用程序的主入口点。
///
[STAThread]
static void Main()
{
//构造连接字符串
string strConnection = "Provider=Microsoft.Jet.OleDb.4.0;";
strConnection += @"Data Source=\\192.168.232.135\access\CSharptest.mdb";
OleDbConnection objConnection = new OleDbConnection(strConnection); //建立连接 objConnection.Open(); //打开连接
OleDbCommand sqlcmd = new OleDbCommand(@"select * from person where personname='John'", objConnection); //sql语句
OleDbDataReader reader = sqlcmd.ExecuteReader(); //执行查询
int age = new int();
if (reader.Read())
{
//这个read调用很重要!不写的话运行时将提示找不到数据
age = (int)reader["age"]; //取得字段的值
objConnection.Close();
reader.Close();
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
form.Text = age.ToString();
Application.Run(form);
}
}
}
运行结果如下: