SQL中的语法不正确?

里斯

我正在使用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());
        }
Soner Gonul

USERT-SQL中保留关键字您应该将其与方括号一起使用[USER]但是,最好的解决方案是将名称更改为非保留字。

始终使用参数化查询此类字符串连接对SQL注入攻击开放

USERUsername的别名您应该在WHERE子句中使用其原始名称

并使用using语句来处理您的SqlConnectionandSqlCommandSqlDataReader

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章