Home > Blockchain >  Syntax error (comma) in query expression ('StudentID', 'Password')
Syntax error (comma) in query expression ('StudentID', 'Password')

Time:04-14

I'm trying to login to my application from my microsoft access database I'm making right now but I'm getting this error "Syntax error (comma) in query expression ('StudentID', 'Password')." Can anyone give me a fix please?

This is the code where the error is coming from:

con.Open();
string login = "SELECT (StudentID, Password) FROM Student WHERE StudentID  = '" txtStudentID  "' and Password = '"   txtPassword   "'";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();

CodePudding user response:

Take off the parentheses:

SELECT StudentID, Password FROM Student ...

And while using parameters to prevent SQL injection is very important (even if this is a school or learning project, as bad habits are hard to break), it is not the source of the problem.

CodePudding user response:

You should remove the parentheses first, also using string interpolation is much better and more readable!

con.Open();
string login = $"SELECT StudentID, Password FROM Student WHERE StudentID  = '{txtStudentID.text}' and Password = '{txtPassword.text}' ";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();

But the complete solution is the below and for avoiding SQL Injection you should use SQL parameters :

SqlParameter userName = new SqlParameter()
            {
                ParameterName = "@UserName",
                DbType = DbType.String,
                Direction = ParameterDirection.Input,
                Value = txtStudentID.text
            };
SqlParameter password = new SqlParameter()
            {
                ParameterName = "@Password",
                DbType = DbType.String,
                Direction = ParameterDirection.Input,
                Value = txtPassword.text
            };
SqlCommand command = new SqlCommand
            {
                Connection = connection,
                CommandType = CommandType.Text,
                CommandText = $"SELECT * FROM Student WHERE StudentID = @UserName and Password = @Password"
            };

 command.Parameters.Add(userName);
 command.Parameters.Add(password);

 con.Open();
 ....
  • Related