简体   繁体   English

MySqlDataReader object 未收到来自 function 的任何数据

[英]MySqlDataReader object not receiving any data from function

I have a post action method which takes in a username and password from a form.我有一个发布操作方法,它从表单中获取用户名和密码。 In this action method I am using a function to execute a mysql command to a database在此操作方法中,我使用 function 对数据库执行 mysql 命令

This is the function to read from the database这是从数据库中读取的 function

public static MySqlDataReader GetDataFromDB(string command)
{
    using (MySqlConnection con = new MySqlConnection(ConStr))
    {

        com = new MySqlCommand(command, con);

        con.Open();

        MySqlDataReader rdr1 = com.ExecuteReader();

        while (rdr1.Read())
        {
                    
        }

        return rdr1;
    }
}

This is how i tried to use this function in my action method这就是我尝试在我的操作方法中使用这个 function 的方式

MySqlDataReader rdr2 = Helper.GetDataFromDB("select * from library.Accounts where username = '" + username + "' and password = '" + password + "'");

I put a breakpoint in the helper method and could see that it was reading from the database fine with it storing all the expected row data in the internal 'rdr1' object however it isnt returning anything at the end as the 'rdr2' object is empty once it's finished.我在辅助方法中放了一个断点,可以看到它正在从数据库中读取数据,它将所有预期的行数据存储在内部的“rdr1”object 但是它最后没有返回任何东西,因为“rdr2”object 是空的一旦完成。 I don't know if something is wrong or if im just being an idiot and so i would appretiate if anyone can tell me where im going wrong.我不知道是不是出了什么问题,或者我只是一个白痴,所以如果有人能告诉我我哪里出错了,我会很感激。

A Data Reader such as MySqlDataReader is Forward Only.诸如MySqlDataReader之类的数据读取器是仅转发的。 This means that once the data has been read and moved on to the next record, or the end of the data, it cannot go back to the beginning.这意味着一旦数据被读取并移动到下一条记录,或者数据的末尾,它就不能 go 回到开头。

If you remove this block of code:如果您删除此代码块:

while (rdr1.Read())
{

}

You should find it will return the Data Reader at the start, and therefore be able to read the data you loaded from the database.您应该会发现它会在开始时返回数据读取器,因此能够读取您从数据库加载的数据。

In addition, you should know that when the using () {...} block finishes the connection will be closed, along with the Data Readers ability to read the data.此外,您应该知道,当 using () {...} 块完成时,连接将关闭,同时数据读取器读取数据的能力也会关闭。

If you do want to return the Data Reader, remove the using() {...} block to be a simple statement like:如果您确实想返回数据读取器,请将 using() {...} 块删除为一个简单的语句,例如:

MySqlConnection con = new MySqlConnection(ConStr);

If you do want to navigate backwards and forwards, filter or sort the data after it has been loaded, you should LOAD the data in to a DataTable from the Data Reader.如果您确实想在数据加载后向后和向前导航、过滤或排序数据,您应该从数据读取器将数据加载到数据DataTable中。

Example:例子:

DataTable dt = new DataTable();
dt.Load(rdr1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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