private void button1_Click(object sender, EventArgs e)
{//采用windows身份验证登录
//ConnectionString 连接的字符串
//Data Source表示服务器的名称,
//Initial Catalog表示数据库 名称
//Integrated Security=True表示采用windows身份登录
//SqlConnection包含了连接连接数据库的字符串
//定义ConnnectionString字符串
// string ConnectionString = @"provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Student.accdb";
string ConnectionString = "Data Source.; Initial Catalog=student; Integrated Security=True;";
SqlConnection conn = new SqlConnection(ConnectionString);//创建SqlConnection对象,ConnectionString表示连接的字符串
string strSql= "Select * from dbo.s_admin where name='"+textBox1.Text.Trim()+"'+password='"+textBox2.Text.Trim()+"'";//定义sql语句
SqlCommand command = new SqlCommand(strSql, conn);//创建SqlConnection对象,并调用构造函数,strSql表示查询字符串,conn表示连接对象名
conn.Open();//打开数据库
//调用SqlCommand对象的ExecuteReader()方法,创建SqlDataReader对象,执行select语句或有返回结果的存储过程
SqlDataReader sqlDataReader = command.ExecuteReader();//将返回的结果集存放到sqlDataReader对象中
try
{
if (sqlDataReader.HasRows == true)//判断是否有返回行
{
MessageBox.Show("登录成功");
MainStudent mainStudent = new MainStudent();//创建MainStudent对象
mainStudent.Show();//显示主界面
this.Hide();//this代表当前对象,隐藏本窗口
}
else
{
MessageBox.Show("账号或者密码错误");
}
}
catch(Exception ex)//捕获异常
{
MessageBox.Show("数据集操作异常" + ex.StackTrace.ToString());
}
finally
{
sqlDataReader.Close();//关闭数据库的连接,SqlDataReader是以独占方法使用SqlConnection对象,必须调用Close()方法断开与SqlConnnection对象
conn.Close();//关闭与数据库的连接
}
}
}
}
相关文章
- C#对于sql server数据库的简单操作
- delphi做的程序如何连接SQL数据库
- springboot报错:解决java连接SQLSERVER数据库之驱动程序无法通过使用安全套接字层(SSL)加密与 SQL Server 建立安全连接的问题
- C#操作sql server之连接sql server数据库
- 使用 IP 地址连接SQL Server 数据库的速度慢的原因
- 用JDBC连接SQL Server2017数据库
- [转载]C#中使用ADO.NET连接SQL Server数据库,自动增长字段用作主键,处理事务时的基本方法
- SQL Server数据库的操作流程和连接的简单介绍
- 解决SQL Server管理器无法连接远程数据库的问题(转)
- 用vs code连接sql server数据库步骤及遇到的问题