从 SQL Server 数据库登录身份验证
Posted
技术标签:
【中文标题】从 SQL Server 数据库登录身份验证【英文标题】:Login Authentication from SQL Server database 【发布时间】:2021-07-19 10:08:21 【问题描述】:我在 Windows 窗体 C# 应用程序上有登录问题身份验证。一旦我注册了用户,它就会将用户数据发送到 SQL Server 数据库。当我尝试登录时。即使凭据与显示的数据库消息框中的数据匹配。请看下面的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using travel_booking.UserControlers;
using System.Data.SqlClient;
namespace travel_booking
public partial class UserContrLogin : UserControl
internal Action<object, EventArgs> OnUserLogin;
UserContrRegister userContrRegister;
public UserContrLogin()
InitializeComponent();
public void setUserContrRegister(UserContrRegister userContrRegister)
this.userContrRegister = userContrRegister;
private void Exit_Click(object sender, EventArgs e)
Application.Exit();
private void LoginButton_Click(object sender, EventArgs e)
SqlConnection sqlConnection = new SqlConnection(@"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = ' " + txtEmail.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
this.Hide();
else
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
sqlConnection.Close();
【问题讨论】:
使用Command Parameters 将值传递给查询,不要连接字符串(你还有一个额外的空间)。不要使用常用术语来命名列(您可以使用名称前缀,例如fPassword
、colPassword
等)。确保您已将存储设置为支持 Unicode。
您还应该使用using
块处理您的连接和适配器
【参考方案1】:
您可以使用此代码更好地工作
public void Login()
SqlConnection sqlConnection = new SqlConnection(@"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = @Email and Password = @Password";
SqlCommand command = new SqlCommand();
command.Connection = sqlConnection;
command.CommandType = CommandType.Text;
command.Text = query;
command.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
command.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if(reader.Read() == true)
this.Hide();
else
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
我使用command.Parameters.AddWithValue()
来避免可能导致SQL INJECTION
【讨论】:
AddWithValue is evil.,指定参数类型和长度。您还应该使用using
块处理您的连接和适配器以上是关于从 SQL Server 数据库登录身份验证的主要内容,如果未能解决你的问题,请参考以下文章
SQL server2000 windows身份验证失败怎么办
SQL server2000 windows身份验证失败怎么办
上次登录sql server 2008后,不小心把里面windows身份验证的 账号删除了, 以后都无法用windows身份验证进
为啥SQL数据库不能用SQL Server身份登录 提示用户sa登录失败。(Microsoft SQL server,错误18456)