我正在使用c#winforms创建用户登录屏幕,我希望能够根据此链接对照SQL数据库中的记录检查用户的用户名和密码,但是我的代码抛出异常,提示“用户附近的语法不正确”。
谁能帮我弄清楚我的代码有什么问题吗?令人反感的代码如下。
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
private void LoginBtn_Click(object sender, EventArgs e)
{
//var username = textBox1.Text;
//var password = maskedTextBox1.Text;
try
{
SqlConnection Conn = new SqlConnection("Data Source=***********;Initial Catalog=*********;Persist Security Info=True;User ID=*********;Password=*******");
SqlCommand com = new SqlCommand();
com.Connection = Conn;
Conn.Open();
com.CommandText = ("SELECT (Username) AS User, (Password) as Pass FROM dbname WHERE User='" + textBox1.Text + "'");
SqlDataReader reader = com.ExecuteReader();
var username = textBox1.Text;
var password = maskedTextBox1.Text;
while (reader.Read())
{
if (this.CompareStrings(reader["User"].ToString(), username) &&
this.CompareStrings(reader["Pass"].ToString(), password))
{
MessageBox.Show("Login Authenticated!");
}
else
{
MessageBox.Show("Login failed!");
}
Conn.Close();
reader.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
USER
是T-SQL中的保留关键字。您应该将其与方括号一起使用[USER]
。但是,最好的解决方案是将名称更改为非保留字。
USER
是Username
列的别名。您应该在WHERE
子句中使用其原始名称。
并使用using
语句来处理您的SqlConnection
andSqlCommand
和SqlDataReader
。
using(SqlConnection Conn = new SqlConnection(connString))
using(SqlCommand com = Conn.CreateCommand())
{
com.CommandText = "SELECT (Username) AS [User], (Password) as Pass FROM dbname WHERE Username = @user";
com.Parameters.AddWithValue("@user", textBox1.Text);
Conn.Open();
using(SqlDataReader reader = com.ExecuteReader())
{
...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句