【发布时间】:2014-06-09 10:43:21
【问题描述】:
我正在 c# winforms 中创建一个用户登录屏幕,我希望能够根据this link, 根据 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] 的用户
-
请使用参数化查询。通过使用未经处理的用户输入构建查询,您的代码很容易受到 SQL 注入的攻击。看起来好像您正在以纯文本形式存储用户凭据...
标签: c# sql sqlcommand