熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

從零開始學ASP.NET(基礎篇 連載五)

2022-06-13   來源: .NET編程 

第五天

學習目的
掌握ADONET打開SQL SERVER數據庫的方法

今天做個非常普通的例子做一個用戶登錄框主要是通過這個練習認識一下SQL SERVER數據庫的連接方法和昨天的例子方法基本相同很容易掌握的
先建立SQL SERVER數據庫庫名為AspNetABC並建立一Member新表建表SQL如下

CREATE TABLE [dbo][Member] (
    [MemberID] [int] IDENTITY ( ) NOT NULL
    [MemberName] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
    [Password] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
    [Gender] [bit] NOT NULL
    [Birthday] [datetime] NULL
    [Email] [nvarchar] () COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]

ALTER TABLE [dbo][Member] WITH NOCHECK ADD 
    CONSTRAINT [PK_Member] PRIMARY KEY CLUSTERED 
    (
        [MemberID]
    ) ON [PRIMARY]

與上一例子差不多在webconfig文件中再增加一行
< appSettings >
    <add key=數據庫 value=exmdb />
    <add key=SqlDatabase value=data source=localhost;user id=sa;password=sa;initial catalog=AspNetABC;Connect Timeout= />
</appSettings>

在面中添加二個文本框txtMemberNametxtPassword並設置txtPassword的TextMode為Password設置按鈕btnLoginbtnLogin的事件代碼如下
private void btnLogin_Click(object sender SystemEventArgs e)
{
    // 先檢驗輸入正確性
    if (txtMemberNameText == StringEmpty || txtMemberNameTextTrim() == )
    {
        ResponseWrite(<script language=javascript>alert(帳號不能為空)</script>);
        return;
    }
    if (txtPasswordText == StringEmpty || txtPasswordTextTrim() == )
    {
        ResponseWrite(<script language=javascript>alert(沒有輸入密碼)</script>);
        return;
    }

    string strConnection = ConfigurationSettingsAppSettings[SqlDatabase];
    string sqlMember = SELECT MemberName [Password] FROM Member
        + WHERE MemberName = + txtMemberNameTextTrim() +
        + AND [Password] = + txtPasswordTextTrim() + ;

    // 連接SqlServer數據庫
    SqlConnection conn = new SqlConnection(strConnection);
    // 建立SqlCommand
    SqlCommand cmd = connCreateCommand();
    cmdCommandText = sqlMember;
    connOpen();
    // 建立DataReader
    SqlDataReader dr = cmdExecuteReader();

    // 判斷DataReader是否為空記錄
    if (drHasRows)
    {
        ResponseWrite(<script language=javascript>alert( + txtMemberNameText + 歡迎你!)</script>);
    }
    else
    {
        ResponseWrite(<script language=javascript>alert(找不到該會員或密碼錯誤)</script>);
    }

    // 千萬不要忘記關閉DataReader
    drClose();

    connClose();
}

好了一個非常簡單的登錄框做好了當然在實際程序中還應加入跳轉等這個就留給你做了

From:http://tw.wingwit.com/Article/program/net/201311/15735.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.