Jared Barrett
Jared Barrett

Reputation: 83

Trouble with SQL syntax

Here is my code.. I'm trying to get it to validate against the database.

pass/user = Admin

{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void main_B_Signup_Click(object sender, RoutedEventArgs e)
    {
        RegWindow rWindow = new RegWindow();
        rWindow.Show();
        this.Close();
    }

    private void main_B_login_Click(object sender, RoutedEventArgs e)
    {
        //connect to the database
        SqlConnection loginConn = new SqlConnection("server=localhost;"+ "Trusted_Connection=yes;" + "database=Production; " + "connection timeout=30");

        SqlCommand cmd = new SqlCommand("Select *from User where Username=' " + this.Main_T_Username.Text + " ' and Password=' " + this.Main_T_Password.Text + " ' ;", loginConn);
        //SqlCommand cmd = new SqlCommand("Select *from User where Username='@Username' and Password='@Password';", loginConn);
        //cmd.Parameters.Add(new SqlParameter("Username", this.Main_T_Username.Text));
        //cmd.Parameters.Add(new SqlParameter("Password", this.Main_T_Password.Text));

        loginConn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        string username = null;

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    username = rdr["Username"].ToString();
                }

                loginConn.Close();

                MessageBox.Show("Well done!");

            }
            else
            {
                MessageBox.Show("WrongPass!");
                loginConn.Close();
            }

        }
    }
}

but the error I get is

Incorrect syntax near the keyword 'User'

But the table is called User and there are columns Username and Password

Pic Of Database

Upvotes: 3

Views: 78

Answers (3)

David
David

Reputation: 219047

"User" is a reserved word in SQL Server. To use it as an identifier for a schema object, surround it with square braces:

SELECT * FROM [User]

It's generally good practice to do this with schema object identifiers anyway. It makes them more explicit in the query.

Additionally, you are:

  • directly concatenating user input as executable code, which is a SQL injection vulnerability. Use query parameters instead.
  • storing user passwords as plain text, which is grossly irresponsible to your users. User passwords should be obscured with a one-way hash and should never be retrievable.

Upvotes: 7

BugFinder
BugFinder

Reputation: 17868

Some words are protected

try

Select * from [User] where Username.....

Upvotes: 0

sparrow
sparrow

Reputation: 980

Put the word User in square brackets like [User] because it's a defined keyword in SQL.

Upvotes: 0

Related Questions