如何在C#登录成功逻辑中访问administracao表的数据库属性?
WinForms登录成功后访问数据库字段的实现方法
核心实现逻辑
当DataTable查询返回有效数据(即登录验证通过)时,你可以直接从DataTable.Rows集合中取出匹配的用户行,再通过数据库字段名访问对应属性值。另外你的原代码存在严重SQL注入风险,必须改为参数化查询,以下是完整优化方案:
优化后的代码
private void button_login_Click(object sender, EventArgs e) { string username = txt_username.Text; string user_password = txt_password.Text; try { // 使用参数化查询,彻底规避SQL注入风险 string query = "SELECT email, name, password, [mobile phone] FROM administracao WHERE email = @Email AND password = @Password"; using (SqlCommand cmd = new SqlCommand(query, conn)) { // 为参数赋值 cmd.Parameters.AddWithValue("@Email", username); cmd.Parameters.AddWithValue("@Password", user_password); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dtable = new DataTable(); sda.Fill(dtable); if (dtable.Rows.Count > 0) { // 获取登录成功的用户数据行 DataRow userRow = dtable.Rows[0]; // 读取四个属性值,带空格的字段需用方括号包裹 string userEmail = userRow["email"].ToString(); string userName = userRow["name"].ToString(); string userPwd = userRow["password"].ToString(); string userMobile = userRow["[mobile phone]"].ToString(); // 部分环境可直接写"mobile phone" // 示例:跳转到主窗体并传递用户信息 Menuform form2 = new Menuform(); // form2.CurrentUserName = userName; // 可将用户信息传递给主窗体 form2.Show(); this.Hide(); } else { MessageBox.Show("登录信息无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); txt_username.Clear(); txt_password.Clear(); txt_username.Focus(); } } } catch (Exception ex) { // 捕获具体异常信息,便于调试 MessageBox.Show($"错误详情:{ex.Message}", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // 确保连接关闭 if (conn.State == ConnectionState.Open) { conn.Close(); } } }
关键注意事项
- 字段名必须与数据库表
administracao中的定义完全一致,带空格的字段(如mobile phone)建议用[mobile phone]包裹,避免语法错误 - 若字段可能为空,需先判断是否为
DBNull再转换,示例:string userMobile = userRow["mobile phone"] != DBNull.Value ? userRow["mobile phone"].ToString() : string.Empty; - 永远不要用字符串拼接的方式写SQL语句,参数化查询是数据库操作的基础安全规范
内容的提问来源于stack exchange,提问作者Pedro Gonçalves
相关产品推荐
相关产品推荐

