locked
Exception in ExecuteScalar()? RRS feed

  • Question

  • User950666261 posted

    Hi,

    I am testing a webservice. Something went wrong in the query. Help me out.

    [WebMethod]
        public int login(string name, string pass)
        {
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\c#\feedback.mdb");
            con.Open();
            OleDbCommand command = con.CreateCommand();
            command.CommandText = "SELECT pass FROM stud where user=" +name;
            command.ExecuteScalar();
            string p = command.ExecuteScalar().ToString();
            con.Close();
            if (pass == p)
            {
                return 1;
            }
            else
                return 0;
        }

    Tuesday, April 21, 2015 3:35 PM

Answers

All replies

  • User-821857111 posted

    Something went wrong in the query.
    What did? What is the exception message?

    command.CommandText = "SELECT pass FROM stud where user=" +name;

    You shouldn't do that. You should use parameters. That will prevent syntax errors:  http://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access

    command.ExecuteScalar();

    string p = command.ExecuteScalar().ToString();

    You are calling executescalar twice?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 21, 2015 4:11 PM
  • User-1716253493 posted

    ExecuteScalar is used to get single value only : SELECT COUNT(*)

    Because you want to get pass value using SELET pass FROM stud WHERE [user] = 'abc'

    The query results can be more than one records or no records, this will causing executescalar error.

    In this case, using ExecuteScalar is not a correct way.

    I think you should use executereader or datatable

    If any record then get the pass value

    Tuesday, April 21, 2015 9:25 PM
  • User950666261 posted

    Thank you for pointing out the mistakes. Solved my problem.

    Wednesday, April 22, 2015 12:09 AM
  • User-821857111 posted

    ExecuteScalar is used to get single value only : SELECT COUNT(*)

    Because you want to get pass value using SELET pass FROM stud WHERE [user] = 'abc'

    The query "SELECT Pass FROM stud WHERE [user] = 'abc'" returns a scalar value. scalar value is one unit of data. This unit of data can be either a number or a chunk of text.

    Wednesday, April 22, 2015 1:58 AM