第五天
学习目的
掌握ADONET打开SQL SERVER数据库的方法
今天做个非常普通的例子做一个用户登录框主要是通过这个练习认识一下SQL SERVER数据库的连接方法和昨天的例子方法基本相同很容易掌握的
先建立SQL SERVER数据库库名为AspNetABC并建立一Member新表建表SQL如下
CREATETABLE [dbo]
[Member] (
[MemberID] [int] IDENTITY ( ) NOTNULL
[MemberName] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOTNULL
[Password] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOTNULL
[Gender] [bit] NOTNULL
[Birthday] [datetime] NULL
[Email] [nvarchar] () COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
ALTERTABLE [dbo][Member] WITHNOCHECKADD
CONSTRAINT [PK_Member] PRIMARYKEYCLUSTERED
(
[MemberID]
) ON [PRIMARY]
与上一例子差不多在webconfig文件中再增加一行
< appSettings >
<addkey=数据库value=exmdb/>
<addkey=SqlDatabasevalue=data source=localhost;user id=sa;password=sa;initial catalog=AspNetABC;Connect Timeout=/>
</appSettings>
在面中添加二个文本框txtMemberNametxtPassword并设置txtPassword的TextMode为Password设置按钮btnLoginbtnLogin的事件代码如下
privatevoid 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();
}
好了一个非常简单的登录框做好了当然在实际程序中还应加入跳转等这个就留给你做了