如何从方法返回DBDataReader,以便调用者可以读取它?

时间:2013-01-29 02:53:58

标签: c# sql task async-await datareader

我创建了这个方法来执行一个返回阅读器的查询。但每次我使用While(Reader.Read()) {}读取结果值时,它都会返回一个异常,如果阅读器已关闭则无法读取。我的方法是否使我的查询动态且可重用有缺陷?显然它是。 =)谢谢!

public async static Task<DbDataReader> SQLQuery(string sqlQuery)
    {
        //INITIALIZE READER THAT WILL BE RETURNED
        DbDataReader reader = null;

        //INSTANTIATE/INITIALIZE NEW SQL DATABASE CONNECTION
        SQLDB newSQL = new SQLDB();

        //OPEN NEW SQL CONNECTION
        ProcessStatus.Echo("Opening MS SQL Connection...");
        if (newSQL.OpenConnection())
        {
            SqlCommand cmd = new SqlCommand(sqlQuery, newSQL.Connection);
            ProcessStatus.Echo("Performing SQL Query...");

            //EXECUTE READER ASYNC
            try
            {
                reader = await cmd.ExecuteReaderAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }

            ProcessStatus.Echo("Done Performing Query. Closing MS SQL Connection...");
            //CLOSE CONNECTION
            newSQL.CloseConnection();
            return (DbDataReader)reader;
        }
        else
        {
            //LOG IF CONNECTION WAS NOT ESTABLISHED
            Console.WriteLine("Could not open SQL Connection. Line 44");
        }
        return reader;
    }

以下是关于我如何称呼它的代码:

        Task<DbDataReader> TReader = SQLDB.SQLQuery("SELECT * FROM TABLE");
        //Other task
        DbDataReader reader = await TReader;

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("I Can Read");
            }
        }
        else
            Console.WriteLine("No Rows Found.");

这将返回错误:

  

关闭阅读器时无效尝试调用HasRows。 (System.InvalidOperationException)

0 个答案:

没有答案