C# 从SQL Server数据库进行登录身份验证
我在windows form C应用程序上有登录问题身份验证。注册用户后,它会将用户数据发送到SQL Server数据库。当我尝试登录时。即使凭证与显示的数据库消息框中的数据匹配。请参阅下面的代码C# 从SQL Server数据库进行登录身份验证,c#,sql-server,windows,visual-studio,winforms,C#,Sql Server,Windows,Visual Studio,Winforms,我在windows form C应用程序上有登录问题身份验证。注册用户后,它会将用户数据发送到SQL Server数据库。当我尝试登录时。即使凭证与显示的数据库消息框中的数据匹配。请参阅下面的代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.T
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();
}
}
}
您可以使用此代码更好地工作
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注入用于将值传递给查询,不要串接字符串,因为您还有额外的空间。不要使用通用术语来命名列。您可以使用前缀作为名称,例如fPassword、colPassword等。。确保已将存储设置为支持Unicode。还应使用USE块处理连接和适配器,并指定参数类型和长度。您还应该使用块来处理连接和适配器