实现的效果图:
代码如下:
//新加命名空间
using System.Data.SqlClient;
using System.Reflection;
//点击"登录"按钮实现数据库验证登录功能
private void button1_Click(object sender, EventArgs e)
{
//字符串赋值:用户名 密码
string username = textBox1.Text.Trim();
string userpwd = textBox2.Text.Trim();
//定义数据库连接语句:服务器=.(本地) 数据库名=TelephoneMS(手机管理系统)
string consqlserver = "Data Source=.;Initial Catalog=TelephoneMS;Integrated Security=True;";
//定义SQL查询语句:用户名 密码
string sql = "select * from Users where username='" + username + "' and userpwd='" + userpwd + "'";
//定义SQL Server连接对象 打开数据库
SqlConnection con = new SqlConnection(consqlserver);
con.Open();
//定义查询命令:表示对数据库执行一个SQL语句或存储过程
SqlCommand com = new SqlCommand(sql, con);
//执行查询:提供一种读取数据库行的方式
SqlDataReader sread = com.ExecuteReader();
try
{
//如果存在用户名和密码正确数据执行进入系统操作
if (sread.Read())
{
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show("请输入正确的用户名和密码");
}
}
catch (Exception msg)
{
throw new Exception(msg.ToString()); //处理异常信息
}
finally
{
con.Close(); //关闭连接
con.Dispose(); //释放连接
sread.Dispose(); //释放资源
}
}