1、建立一個Access數(shù)據(jù)庫名為CSharpTest.accdb,里面有一個Person表,它有三個字段ID、PersonName和Age,分別是自動增長列、文本和數(shù)字類型。并插入兩條記錄,如下所示: - PersonnNme Age
- lishi 30
- wangwu 20
2、打開VS2008,菜單中點"文件"->"新建"->"項目"->"網(wǎng)站"->"ASP.NET網(wǎng)站",建立一個新的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./TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www./1999/xhtml">
- <head runat="server">
- <title>Access2007數(shù)據(jù)庫操作</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Label ID="Label1" runat="server" Text="這是Access數(shù)據(jù)庫查詢出來的{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連接數(shù)據(jù)庫的方法
- /// </summary>
- protected void AccessConnectionDB()
- {
- string strConnection = "Provider = Microsoft.ACE.OLEDB.12.0;"; //C#讀取Excel的連接字符串
- strConnection += @"Data Source = E:/Access/CSharpTest.accdb "; //指定數(shù)據(jù)庫在硬盤的物理位置
- 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()) //執(zhí)行查詢,用using替代reader.Close()
- {
- if (reader.Read()) //這個read調用很重要!不寫的話運行時將提示找不到數(shù)據(jù)
- {
- age = (int)reader["age"]; //取得字段的值
- name = reader["PersonName"].ToString(); //取得字段的值
- }
- }
- }
- this.Label1.Text = string.Format(this.Label1.Text, name, age);
- }
- }
|