C#连接Access2007数据库代码实例完整版

1、建立一个Access数据库名为CSharpTest.accdb,里面有一个Person表,它有三个字段ID、PersonName和Age,分别是自动增长列、文本和数字类型。并插入两条记录,如下所示: PersonnNme Age lishi 30 wangwu 20

2、打开VS2008,菜单中点"文件"->"新建"->"项目"->"网站"->"ASP.NET网站",建立一个新的Web站点。 

3、在Default.aspx页面文件中添加一个"label"服务器控件。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Access2007数据库操作</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="这是Access数据库查询出来的{0}的年龄:{1}岁"></asp:Label> </div> </form> </body> </html>

4、修改代码文件Default.aspx.cs的内容,其完整C#代码如下

 

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { AccessConnectionDB(); } /// <summary> /// Access连接数据库的方法 /// </summary> protected void AccessConnectionDB() { string strConnection = "Provider = Microsoft.ACE.OLEDB.12.0;"; //C#读取Excel的连接字符串 strConnection += @"Data Source = E:/Access/CSharpTest.accdb "; //指定数据库在硬盘的物理位置 int age = 0; string name = ""; using (OleDbConnection objConnection = new OleDbConnection(strConnection)) //用using替代objConnection.Close() { objConnection.Open(); //打开连接 OleDbCommand sqlcmd = new OleDbCommand(@"select * from Person where PersonName='lishi'", objConnection); //sql语句 using (OleDbDataReader reader = sqlcmd.ExecuteReader()) //执行查询,用using替代reader.Close() { if (reader.Read()) //这个read调用很重要!不写的话运行时将提示找不到数据 { age = (int)reader["age"]; //取得字段的值 name = reader["PersonName"].ToString(); //取得字段的值 } } } this.Label1.Text = string.Format(this.Label1.Text, name, age); } }   

你可能感兴趣的:(数据库,XHTML,server,C#,asp.net,Access)