第五天
学习目的:
掌握ADO.NET打开SQL SERVER数据库的方法。
今天做个非常普通的例子,做一个用户登录框。主要是通过这个练习认识一下SQL SERVER数据库的连接方法。和昨天的例子方法基本相同,很容易掌握的。
先建立SQL SERVER数据库,库名为AspNetABC,并建立一Member新表,建表SQL如下:
CREATE TABLE [dbo].[Member] (
[MemberID] [int] IDENTITY (1, 1) NOT NULL ,
[MemberName] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Password] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Gender] [bit] NOT NULL ,
[Birthday] [datetime] NULL ,
[Email] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[Member] WITH NOCHECK ADD
CONSTRAINT [PK_Member] PRIMARY KEY CLUSTERED
(
[MemberID]
) ON [PRIMARY]
与上一例子差不多,在web.config文件中再增加一行:
<appSettings>
<add key="数据库1" value="ex01.mdb" />
<add key="SqlDatabase1" value="data source=localhost;user id=sa;password=sa;initial catalog=AspNetABC;Connect Timeout=30" />
</appSettings>
在面中添加二个文本框,txtMemberName、txtPassword,并设置txtPassword的TextMode为Password。设置按钮btnLogin。btnLogin的事件代码如下:
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["SqlDatabase1"];
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();
}
好了,一个非常简单的登录框做好了。当然在实际程序中还应加入跳转等,这个就留给你做了。