如果以其他形式打开数据阅读器如何关闭应用程序 [英] how to close data reader if it is open in other forms ,application

查看:87
本文介绍了如果以其他形式打开数据阅读器如何关闭应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//This Is my data What ever m using
  SqlDataReader reader;

            DateTime dt1 = Convert.ToDateTime(dateTimePicker1.Text);
            DateTime dt2 = Convert.ToDateTime(dateTimePicker2.Text);

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = getConnection();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = sp_name;

            SqlParameter P1 = new SqlParameter();
            P1.Direction = ParameterDirection.Input;
            P1.SqlDbType = SqlDbType.DateTime;
            P1.ParameterName = "@FromDate";
            P1.Value = dt1;
            cmd.Parameters.Add(P1);

            SqlParameter P2 = new SqlParameter();
            P2.Direction = ParameterDirection.Input;
            P2.SqlDbType = SqlDbType.DateTime;
            P2.ParameterName = "@ToDate";
            P2.Value = dt2;
            cmd.Parameters.Add(P2);
         
            reader = cmd.ExecuteReader();

//I Got error here that "Invalid attempt to call Read when reader is close"

            while (reader.Read())
            {
              

                DateTime dt = (DateTime)reader["TimeStamp"];         
                int milliSeconds = dt.Millisecond;
                s = dt.ToString("dd-MM-yyyy HH:mm:ss.fff");
                checkedListBox1.Items.Add(s);
                
            }
            return 0;
         





请给我解决方案



Please Give me solution

推荐答案

好吧,看起来你正试图为结果集中的每一行创建一个新的DataTable。这听起来像个坏主意。我怀疑是Load方法处理读者,所以在下一次迭代中它会抱怨,但这只是一个有根据的猜测。



无论哪种方式,你都希望得到读取数据并尽快关闭。填充数据表并使用它。
Well, it looks like you are trying to create a new DataTable for each row in the result set. That sounds like a bad idea. My suspicion is that the Load method disposes of the reader so in the next iteration it complains, but that's just an educated guess.

Either way, you want to get the data out of the reader and close it as quickly as you can. Fill the datatable and use that.


Hi Dipika,



您可以使用关闭方法SqlDataReader对象关闭当前的datareader,当你完成你的过程时,这应该是下一个。



例如
Hi Dipika,

You can use Close method for SqlDataReader object to close the current datareader, and this should be very next when you complete your process.

e.g
reader.Close();







在您提到的上述评论中检查




in the above comment you mention to check

if(connect.State == ConnectionState.Closed)
{
connect.Open();
}



你能告诉我对象connect是你的SqlConnection类的对象。如果是,那么你正在正确检查连接。



关闭当前打开的连接为SqlConnection类使用




could you please let me know object "connect" is the object for your SqlConnection class. if so then you are doing right checking for connection.

to close the current open connection for SqlConnection Class use

if(connect.State== ConnectionState.Open)
{
connect.Close();
}


这篇关于如果以其他形式打开数据阅读器如何关闭应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆