您的位置:首页 > 数据库

ADO.NET 使用Connection对象连接数据库实现用户登录

2017-03-04 17:34 731 查看
今天想总结一下上周老师讲的用Connection对象连接字符串实现登录的demo。

也想将代码熟悉一下。

首先在sql server中建好表,我只设置了两个字段 :usrName和psd。

接下来在vs中建一个login的windows窗体应用程序(其他的类型程序也可以,代码是一样的)

当然需要先了解一下给对象之间的关系,如下图:



先在下窗体设计器中加上按钮,文本框等,界面如下:

然后添加按钮,双击添加函数,代码如下,已经添加注释,写在了登录按钮里面。



private void btuLogin_Click(object sender, EventArgs e)
{
string usrName = this.userName.Text.Trim();
string psd = this.psd.Text.Trim();

string connectionstring = @"Server = AFOC-1702201437\SQLEXPRESS; User ID=sa; password = 0903. ; Database = Test";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionstring;
conn.Open();
//MessageBox.Show("数据库打开成功!");

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select  *  from userInfo where userName ='" + usrName + " 'and psd = '" + psd + "';";
cmd.Connection = conn;

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
int i = 0;
try
{
da.Fill(ds);
i = ds.Tables[0].Rows.Count;
}
catch (Exception exp)
{

MessageBox.Show(exp.Message.ToString());
}

if (ds.Tables[0].Rows.Count > 0)
{
MessageBox.Show("登录成功!");
}
else
{
MessageBox.Show("UserName or Password has error!");
this.userName.Text = string.Empty;
this.psd.Text = string.Empty;
return;
}

conn.Close();

}


“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库
相关文章推荐