// 代码中引入命名空间的代码极其重要,切勿忘记(using System.Data.SqlClient;)web
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; /*引入命名空间*/ namespace _8_6_链接数据库验证登陆 { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { string Admin = "Data Source = DESKTOP-3HVKRJT; Initial Catalog = 学生验证和信息系统; User ID = sa; " + "Pwd = 66470088;"; // 用户服务器名称; 数据库名称; 用户名称; 用户登陆密码 public MainForm() { InitializeComponent(); } void TextBox1TextChanged(object sender, EventArgs e) // 学号 文本框 { // 验证文本框的字符长度 if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0) { button1.Enabled = true; } else if (textBox1.Text.Length > 0 || textBox2.Text.Length >0) { button1.Enabled = false; } } void TextBox2TextChanged(object sender, EventArgs e) // 密码 文本框 { // 验证文本框的字符长度 if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0) { button1.Enabled = true; } else if (textBox1.Text.Length > 0 || textBox2.Text.Length >0) { button1.Enabled = false; } } void Button1Click(object sender, EventArgs e) // 登陆 按钮 { // 1.链接数据库 SqlConnection connection1 = new SqlConnection(Admin); // 链接数据库的字符串 connection1.Open(); // 打开数据库链接 // 2.查询 学号 密码 是否相同 string select1 = "select * from 用户密码表 where 学号= '"+textBox1.Text+"' "+" " + "and 密码= '"+textBox2.Text+"' "; // 拼接字符串(学号) SqlCommand command1 = new SqlCommand(select1,connection1); // 3.使用 DataReader 保存查询结果 SqlDataReader sqldatareader1 = command1.ExecuteReader(); // 储存查询结果(学号) if (sqldatareader1.Read()) { MessageBox.Show("登陆成功。"); } else { MessageBox.Show("学号或密码输入错误,请从新输入。"); } connection1.Close(); // 关闭数据库链接 } } }