使用VS2013與內置數據庫進行連接

一、頁面的佈置

1、首先需要將頁面做好(本例的工程名爲demo,框架用的是.NET Framework 4.5)。示例頁面代碼如下:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="demo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>登錄</title>
</head>
<body>
    <form id="form1" runat="server">
        歡迎來到校園活動預約系統
    <table>
        <tr><td>用戶名:</td><td><asp:TextBox ID="username" runat="server"></asp:TextBox></td></tr>
        <tr><td>密碼:</td><td><asp:TextBox ID="userpwd" runat="server" TextMode="Password"></asp:TextBox></td></tr>
        <tr><td>身份:</td><td><asp:DropDownList ID="DropDownListLevel" runat="server"></asp:DropDownList></td></tr>
        <tr><td colspan="2"><asp:Button ID="ButtonOK" runat="server" Text="登 錄" OnClick="ButtonOK_Click" /></td></tr>
        <tr><td colspan="2"><asp:Label ID="LabelLoginInf" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td></tr>
    </table>
    </form>
</body>
</html>

 

2、本例是登錄測試,首先查詢數據庫用戶名、密碼、用戶類型是否一一對應。如果對應,提示登錄成功,並轉入相應頁面;如果不對應,則提示用戶名或密碼錯誤,請重新輸入。

 

二、引用數據庫類代碼

1、這裏選用BaseClass.cs文件作爲數據庫操作類,也可選用網上常用的SQLHelper類文件。將文件放入App_Code文件夾中,沒有的話新建一個。示例代碼如下所示:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
///BaseClass 的摘要說明
/// </summary>
namespace GROUP.Manage
{
    public class BaseClass:System.Web.UI.Page
    {
        String strConn;
        //構造函數
        public BaseClass()
        {
            //
            //TODO: 在此處添加構造函數邏輯
            //
            strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        }
        //從數據庫中讀取數據,返回DataTable對象
        public DataTable ReadTable(String strSql)
        {
            DataTable dt = new DataTable();
            SqlConnection Conn = new SqlConnection(strConn);
            Conn.Open();
            SqlDataAdapter Cmd = new SqlDataAdapter(strSql, Conn);
            Cmd.Fill(dt);
            Conn.Close();
            return dt;
        }
        //從數據庫中讀取數據,返回DataSet對象
        public DataSet ReadDataSet(String strSql)
        {
            DataSet ds = new DataSet();
            SqlConnection Conn = new SqlConnection(strConn);
            Conn.Open();
            SqlDataAdapter Cmd = new SqlDataAdapter(strSql, Conn);
            Cmd.Fill(ds);
            Conn.Close();
            return ds;
        }
        //從數據庫中讀取數據,返回DataSet對象(需要表名)
        public DataSet GetDataSet(String strSql,String tableName)
        {
            DataSet ds = new DataSet();
            SqlConnection Conn = new SqlConnection(strConn);
            Conn.Open();
            SqlDataAdapter Cmd = new SqlDataAdapter(strSql, Conn);
            Cmd.Fill(ds,tableName);
            Conn.Close();
            return ds;
        }
        //執行SQL查詢,並返回一個Reader對象
        public SqlDataReader readrow(String sql)
        {
            SqlConnection Conn = new SqlConnection(strConn);
            Conn.Open();
            SqlCommand Comm = new SqlCommand(sql, Conn);
            SqlDataReader Reader = Comm.ExecuteReader();
            if (Reader.Read())
            {
                Comm.Dispose();
                return Reader;
            }
            else
            {
                Comm.Dispose();
                return null;
            }
        }
        //返回查詢結果第一行某一個字段的值
        public string ReadStr(String strSql, int flag)
        {
            DataSet ds = new DataSet();
            String str;
            SqlConnection Conn = new SqlConnection(strConn);
            Conn.Open();
            SqlDataAdapter Cmd = new SqlDataAdapter(strSql, Conn);
            Cmd.Fill(ds);
            str = ds.Tables[0].Rows[0].ItemArray[flag].ToString();
            Conn.Close();
            return str;
        }
        //執行SQL更新語句
        public void execsql(String strSql)
        {
            SqlConnection Conn = new SqlConnection(strConn);
            SqlCommand Comm = new SqlCommand(strSql,Conn);
            Conn.Open();
            Comm.ExecuteNonQuery();
            Conn.Close();
        }
    }
}

 

2、主要使用的方法有兩個,一個是ReadTable方法(此方法是從數據庫中讀取相應的查詢語句組成的表,即查詢操作),另一個是execsql方法(此方法用於插入、更新、刪除語句)。

 

三、設計數據庫

(1)首先從視圖菜單中打開SQL Server對象資源管理器。

(2)單擊SQL Server,將下面的數據庫打開,在“數據庫”項下新建一個數據庫作爲本例使用的數據庫。

(3)新建一個表,作爲本例使用的表。數據庫輸入之後,在下面更改表名,然後點更新,對數據庫進行保存操作。如下圖所示:

(4)更新好後,數據庫表中就會多出剛纔的表。

(5)增加數據。右擊剛纔新建的表,選擇查看數據。此處增加的是用戶名爲admin,密碼爲123456。如下所示

 

四、數據庫連接

在解決方案資源管理器中打開Web.config配置文件。插入以下代碼

<connectionStrings>

    <add name="ConnectionString" connectionString="...此處內容選取新建好的數據庫的屬性的連接字符串..."/>

</connectionStrings>

連接字符串查找(右擊數據庫,選屬性,從右側的屬性列表裏找連接字符串):

 

五、在頁面的cs文件中調用數據庫操作代碼

(1)首先修改引用操作類代碼文件。將引用的操作代碼cs文件屬性的內容改爲編譯。然後對本例解決方案進行生成操作。

(2)在頁面的cs文件中使用using引用數據庫操作類的命名空間。

            (例如此處是using GROUP.Manage;)

(3)書寫代碼,調用數據庫,獲取數據。(示例代碼如下)

BaseClass BaseClass1 = new BaseClass();
        protected void Page_Load(object sender, EventArgs e)
        {
            GetDPListValue();
        }
        protected void GetDPListValue()
        {
            DataSet ds = new DataSet();
            ds.Tables.Add("DPList");
            ds.Tables["DPList"].Columns.Add("UserLevelNum", typeof(int));
            ds.Tables["DPList"].Columns.Add("UserLevelText", typeof(string));
            ds.Tables["DPList"].Rows.Add(new object[] { 1, "管理員" });
            ds.Tables["DPList"].Rows.Add(new object[] { 2, "組織者" });
            ds.Tables["DPList"].Rows.Add(new object[] { 3, "參與者" });
            DropDownListLevel.DataSource = ds.Tables["DPList"];
            DropDownListLevel.DataValueField = "UserLevelNum";
            DropDownListLevel.DataTextField = "UserLevelText";
            DropDownListLevel.DataBind();
        }

        protected void ButtonOK_Click(object sender, EventArgs e)
        {
            string status = DropDownListLevel.SelectedValue.ToString().Trim();  //獲取下拉列表的值
            string strsql;
            strsql = "select * from [AMUser] where UserName='" + username.Text + "' and UserPassword='" + userpwd.Text + "' and UserLevel='" + status + "'  and IsDeleted='0'";
            DataSet ds = new DataSet();
            ds = BaseClass1.GetDataSet(strsql, "amuser");
            if (ds.Tables["amuser"].Rows.Count == 0)
            {
                LabelLoginInf.Text = "輸入的用戶名或密碼錯誤!";
            }
            else
            {
                Session["UserName"] = username.Text.ToString();
                Session["UserID"] = "";
                String level = DropDownListLevel.SelectedValue.ToString().Trim();
                //下面可以根據不同的需要(根據用戶等級)進入相應的頁面
                LabelLoginInf.Text = "登錄成功!";
                Response.Write("<script>alert('登錄成功!即將進入系統……');window.location.href='#';</script>");
            }
        }

 

六、完成並進行網頁測試

 

發佈了31 篇原創文章 · 獲贊 116 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章