C#密码连接SQL数据库

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();   // 关闭数据库连接
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rsZheng4916

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值