基于C# Windows Form与SQL实现登录后主窗体显示Display_Name
修改登录后主窗体显示Display_Name的实现方案
核心改动思路
原来的SQL仅验证账号密码并返回匹配数,现在需要同时查询并获取对应用户的Display_Name,再将其传递给主窗体显示。
修改后的完整代码
string inputUsername = textBox1.Text; string inputPassword = textBox2.Text; // 使用using自动释放数据库连接资源 using (SqlConnection connection = new SqlConnection("Data Source = 192.168.105.30; Initial Catalog = testDB; User ID = sa; Password = 123456")) { connection.Open(); // 修改SQL语句:验证账号密码的同时查询Display_Name string sqlQuery = "SELECT Display_Name FROM Coke_User WHERE Username=@Username AND Password=@Password"; using (SqlCommand sqlCommand = new SqlCommand(sqlQuery, connection)) { sqlCommand.Parameters.AddWithValue("@Username", inputUsername); sqlCommand.Parameters.AddWithValue("@Password", inputPassword); // 执行查询,返回Display_Name或null object result = sqlCommand.ExecuteScalar(); if (result != null) { string displayName = result.ToString(); // 替换为Display_Name显示欢迎信息 UserName.Name = $"Hello {displayName}, Welcome to COKE."; Form1 form1 = new Form1(); form1.Show(); this.Hide(); } else { MessageBox.Show("You have entered wrong credentials!"); } } }
关键改动说明
- SQL查询调整:将
SELECT COUNT(*)改为SELECT Display_Name,既完成账号密码验证,又直接获取需要显示的昵称字段。 - 结果判断逻辑:通过
ExecuteScalar()返回的结果是否为null判断登录是否成功(无匹配用户时返回null)。 - 资源优化:添加
using语句包裹SqlConnection和SqlCommand,确保数据库连接等资源自动释放,避免连接泄漏。 - 显示内容替换:将原来拼接
Username的逻辑改为使用查询到的Display_Name。
内容的提问来源于stack exchange,提问作者Pappu
相关产品推荐
相关产品推荐

