第五天
學習目的
掌握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=
ex
mdb
/>
<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
System
EventArgs e)
{
// 先檢驗輸入正確性
if (txtMemberName
Text == String
Empty || txtMemberName
Text
Trim() ==
)
{
Response
Write(
<script language=javascript>alert(
帳號不能為空
)</script>
);
return;
}
if (txtPassword
Text == String
Empty || txtPassword
Text
Trim() ==
)
{
Response
Write(
<script language=javascript>alert(
沒有輸入密碼
)</script>
);
return;
}
string strConnection = ConfigurationSettings
AppSettings[
SqlDatabase
];
string sqlMember =
SELECT MemberName
[Password] FROM Member
+
WHERE MemberName =
+ txtMemberName
Text
Trim() +
+
AND [Password] =
+ txtPassword
Text
Trim() +
;
// 連接SqlServer數據庫
SqlConnection conn = new SqlConnection(strConnection);
// 建立SqlCommand
SqlCommand cmd = conn
CreateCommand();
cmd
CommandText = sqlMember;
conn
Open();
// 建立DataReader
SqlDataReader dr = cmd
ExecuteReader();
// 判斷DataReader是否為空記錄
if (dr
HasRows)
{
Response
Write(
<script language=javascript>alert(
+ txtMemberName
Text +
歡迎你!
)</script>
);
}
else
{
Response
Write(
<script language=javascript>alert(
找不到該會員
或密碼錯誤
)</script>
);
}
// 千萬不要忘記關閉DataReader
dr
Close();
conn
Close();
}
好了一個非常簡單的登錄框做好了當然在實際程序中還應加入跳轉等這個就留給你做了
From:http://tw.wingwit.com/Article/program/net/201311/15735.html