愤斗的程序猿丷
Keep on going never give up.
posts - 20,comments - 4,views - 14万
复制代码
 1 /*通过C#winform程序访问数据库数据
 2 
 3 用到的命名空间和变量类型:
 4 
 5 using System.Data.SqlClient;
 6 
 7 SqlConnection;数据库连接类
 8 
 9 SqlCommand;数据库操作类
10 
11 SqlDataReader:读取 */
12 
13 //登录按钮代码
14 private void button1_Click(object sender, EventArgs e) 
15 {
16 if (textBox1.Text == "")
17 MessageBox.Show("用户名不能为空!", "提示");
18 else if (textBox2.Text == "")
19 MessageBox.Show("密码不能为空!", "提示");
20 try //try...catch...异常处理语句
21 {
22 string name, pass;
23 bool flag = false;
24 name = textBox1.Text;
25 pass = textBox2.Text; //获取用户名,密码
26 string str = "Data Source=SQL服务器名称;Initial Catalog=数据库名;User ID=登录名;Password=密码;";
27 SqlConnection myConn = new SqlConnection(str);//创建数据库连接类的对象
28 myConn.Open(); //将连接打开
29 //SQL语句:从数据库的登录表中搜索登录名,密码
30 string sqlstring = "select username,password from users where username='" +name + "'and password='" + pass + "'"; 
31 //执行con对象的函数,返回一个SqlCommand类型的对象
32 SqlCommand command = new SqlCommand(sqlstring, myConn);
33 //用cmd的函数执行语句,返回SqlDataReader对象thisReader,thisReader就是返回的结果集(也就是数据库中查询到的表数据)
34 SqlDataReader thisReader = command.ExecuteReader();
35 //判断用户名及密码是否正确,对flag进行赋值
36 while (thisReader.Read()) 
37 {
38 if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim()))
39 {
40 if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim())
41 {
42 flag = true;
43 }
44 }
45 }
46 //用完后关闭连接,以免影响其他程序访问
47 myConn.Close(); 
48 if (flag)
49 {
50 MessageBox.Show("登陆成功!");
51 Form2 F = new Form2(); //显示主页面
52 F.Show();
53 this.Hide();
54 }
55 else
56 {
57 MessageBox.Show("请检查你的用户名和密码!");
58 textBox1.Focus();
59 }
60 }
61 catch (Exception ex2)
62 {
63 MessageBox.Show("连接远程SQL数据库发生错误:" + ex2.ToString(), "错误!");
64 }
复制代码

 

posted on   愤斗的程序猿丷  阅读(23317)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示