【发布时间】:2022-01-13 15:43:33
【问题描述】:
我已经阅读了这个论坛中提供的关于这个问题的许多问题和答案,应用了许多不同的方法并多次更改我的代码,我什至不记得原来的了。
我在以下行中不断收到此错误:
SqlDataReader dr;
错误是
System.Data.SqlClient.SqlException: '';' 附近的语法不正确。'
我在这方面完全是个菜鸟,我是自学的,所以我道歉。
这是在 App.Config 中
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=SolAquaMasterDdata;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
我在主窗体上的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace SolTry
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
public MainWindow()
{
InitializeComponent();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
}
private void BtnLogin_Click(object sender, RoutedEventArgs e)
{
string User = txtUsername.Text;
string Pass = txtPassword.Password;
string str1 = "Please enter a valid Username and Password.";
string str2 = "The credentials entered do not match any registed users.";
string str3 = "These login credentials are correct.";
conn.Open();
cmd.Connection = conn;
SqlDataReader dr;
cmd.CommandText = ("SELECT Status, UserName, Password FROM tblUsers WHERE UserName = @Username and Password = @Password;");
using (conn)
{
//help add parameterization - missing
dr = cmd.ExecuteReader();
if ((string.IsNullOrEmpty(User)) && (string.IsNullOrEmpty(Pass)))
{
MessageBox.Show(str1, "NO CREDENTIALS ENTERED", MessageBoxButton.OK, MessageBoxImage.Error);
}
if ((string.IsNullOrEmpty(User)) == false && (string.IsNullOrEmpty(Pass)) == false)
{
if (dr.HasRows.Equals(true))
{
MessageBox.Show(str3, "LOGIN SUCCESSFUL", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dr.HasRows == false)
{
MessageBox.Show(str2, "INVALID CREDENTIALS", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
conn.Close();
}
private void ExitApp(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
DragMove();
}
}
}
无论我尝试过什么,我总是失败。
我要做的就是在点击登录表单按钮时验证 tblUsers 中的用户名和密码是否正确,然后检查状态是否为“true”或 1
请告诉我如何参数化 sql
【问题讨论】:
-
不,
SqlDataReader dr;可能不是您收到此特定错误的行。 -
WHERE 缺少右括号。应该是:txt.Password);");
-
查询还应将
txt.Password和txt.Username的文本值放入参数并将这些参数添加到命令中。 -
您想要传递
txt.Password的值这一事实强烈表明您正在存储纯文本密码。这是一个巨大的安全漏洞。 始终对您的密码进行加盐和哈希处理。 -
@jdweng 我建议它不是缺少一个,它有一个无关紧要的;
WHERE根本不需要用括号括起来。
标签: c# sql-server visual-studio