C#密码连接SQL数据库
1.SQL表格数据类型和记录
2.C#执行结果
3.C#代码
// 代码中引入命名空间的代码极其重要,切勿忘记(using System.Data.SqlClient;)
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(); // 关闭数据库连接
}
}
}