实验目的:
学习连接数据库。
实验内容:
使用Visual Studio编写一个登录系统,并且该系统还需要连接数据库
目标效果:
实验步骤:
1、数据库数据准备:
需要在数据库里准备一张关于登录的表,以便下面可以进行使用
2、创建新项目:
3、根据目标效果从工具箱添加控件:
初步效果:
4、按钮’OK"的点击事件:
(1)取出文本TextBox里的文本
string username = textBox1.Text.Trim();//取出账号
string password = textBox2.Text.Trim();//取出密码
(2)连接、打开并使用数据库,使用完毕需要关闭数据库
string myConnString = "Data Source=.;Initial Catalog=Student;Persist Security Info=True;User ID=sa;Password=*********";
//此处我的密码用*代替
SqlConnection sqlConnection = new SqlConnection(myConnString);//实例化连接对象
sqlConnection.Open();//打开数据库
string sql = "select UserId,Password from UserTable where UserId = '" + username + "' and Password = '" + password + "'"; //编写SQL命令
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows)
{
MessageBox.Show("WELCOME!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);