简体   繁体   中英

Getting DataSet ds.Tables[0].Rows.Count=0

Hi I am developing an application in VS 2010 C# and MySql

I have a function to validate is provided credentials are exist or not. Code is as below.

private bool Validate(string studentId, string time)
    {
        var msCon = _dal.OpenMySQLConnection();
        var da = new MySqlDataAdapter("SELECT * FROM tblStudent where Registeration_Date='" + time.Trim() + "' and studentId='" + studentId.Trim() + "' order by date_time desc limit 1", msCon);
        var ds = new DataSet();
        da.Fill(ds);
        var count = ds.Tables[0].Rows.Count;
        if (count == 0)
        {
            updateOrExist.Text = @"E";
            updationTime.Text = @"Current Checked Time: " +  DateTime.Now.ToShortTimeString();
            return true;
        }
        updationTime.Text = @"Current updated Time: " + DateTime.Now.ToShortTimeString();
        return false;
    }

In this there is already registered student with matching result but still I am getting count=0. Don't know how.

Requeting your suggestions.

First, you are open for sql-injection, use sql-parameters instead of string concatenation.

According to your actual issue, i must admit that i'm not sure what causes the problem. But using parameters with the correct types often solves such issues:

private bool Validate(string studentId, string time)
{
    DateTime registrationDate;
    if (!DateTime.TryParse(time.Trim(), out registrationDate))
        throw new ArgumentException("Time must be convertible to datetime", "time");
    int id;
    if (!int.TryParse(studentId.Trim(), out id))
        throw new ArgumentException("StudentId must be convertible to Integer", "studentId");
    string sql = @"
        SELECT * FROM tblStudent 
        WHERE   Registeration_Date=?Registeration_Date 
        AND     StudentID=?StudentID 
        ORDER BY date_time desc 
        limit 1";
    using (var msCon = new MySqlConnection("connection-string"))
    using (var da = new MySqlDataAdapter(sql, msCon))
    {
        da.SelectCommand.Parameters.AddWithValue("?Registeration_Date", registrationDate);
        da.SelectCommand.Parameters.AddWithValue("?StudentID", id);

        var table = new DataTable();
        da.Fill(table);
        return table.Rows.Count = 1;
    }
}

I had the same problem, more info, the sql database returns 0 row(s) but da.Tables(0).Rows.Count=1.

My problem was that before this check, I used the dataset in another SQL query. REMEMBER ALWAYS TO RESET THE DATASET BEFORE NEW SQL QUERY ANSWER, or you will have problems.

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