简体   繁体   中英

Cannot retrive data using dataset from database

I am writing web service method to retrieve the data of the user. To make clear, I have a table called User in my database, which has, ID, fName, lName, emailAddress, username, password, reg_ID. If i used the ID to retrieve the data, it will work but instead if i use emailAddress in "where" clause, it gives me following error.

Web service method

 [WebMethod(Description = "Returns Details of User with username")]
        public DataSet GetUser(string user)
        {
            DataSet dataSet = new DataSet();
            OleDbConnection oleConn = new OleDbConnection(connString);

            try
            {
                oleConn.Open();
                string sql = "SELECT * FROM [User] WHERE [username]=" + user;
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
                dataAdapter.Fill(dataSet, "User");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                oleConn.Close();
            }
            if (dataSet.Tables["User"].Rows.Count <= 0)
                return null;

                return dataSet;
        }

Error

System.NullReferenceException: Object reference not set to an instance of an object.
   at UserManagement.UserRegistration.GetUser(String user) in C:\Users\smartamrit\Desktop\SystemSoftware\UserManagement\UserRegistration.asmx.cs:line 170

Line 170 starts at if (dataSet.Tables["User"].Rows.Count <= 0 )

If the query does not return any rows, no tables are added to the DataSet. Thus

dataSet.Tables["User"]

is probably null.

You need to check the return value of the Fill method to ensure that rows were returned.

Per MSDN documentation the fill method returns an integer which represents:

The number of rows successfully added to or refreshed in the DataSet. This does not include rows affected by statements that do not return rows.

Furthermore, your query is open to sql injection (a security vulnerability). You will want to change it to use parameterized queries instead.

Did you use single quotes while passing the email id or try to use like statement when passing email id. Have you check whether any exception raises in the catch block.

The possible reason is there may occur a exception in catch block, it was suppressed and after that the if statement has executed and throwed a error that user table was not found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM