mysqldatareader什么意思_声明MySqlDataReader而不初始化它

I want to declare a MySqlDataReader, without initialising it or assigning any value to it. Like the code below.

MySqlDataReader rdr;

try

{ /* stuff to open the MySqlDataReader and use it, not important for my question */ }

catch (Exception e)

{ /* error handling stuff, not important for my question */ }

finally

{

/* code to close the reader when things have gone wrong */

try

{

if (rdr != null)

{

if (rdr.IsClosed == false)

{

rdr.Close();

}

}

}

catch (Exception e)

{ /* error handling stuff, not important for my question */ }

}

The reason for that is I want to close the MySqlDataReader in a finally section of the try if it does in fact I do get a run time error. So the MySqlDataReader has to be declared before of the try, otherwise it'll be out of scope for the finally code.

However when I compile the code above I get the compile time error "Use of unassigned local variable 'rdr'" so I want to set it to something for example

MySqlDataReader rdr = New MySqlDataReader();

But this give me a compile time error "The type 'MySql.Data.MySqlClient.MySqlDataReader' has no constructors defined". And assigning the result of a command object will make the code compile however that can go wrong and is what my try is trying to catch.

When this function is called for a second time if the MySqlDataReader object is not closed from the first iteration, then it will crash second time around.

So how do I clean up my MySqlDataReader objects when things go wrong?

Solutions1

Just assign it with null. The compiler will know a value has assigned, although it is null.

MySqlDataReader rdr = null;

In your finally block, check on the null value.

MySqlDataReader rdr = null;

try

{

... // do stuff here

}

finally

{

if (rdr != null)

{

// cleanup

}

}

Or use using if possible. It will cleanup rdr for you:

using (MySqlDataReader rdr = ... )

{

}

Solutions2

One option is to initialize it to null to start with:

MySqlDataReader rdr = null;

After all, you're already checking whether it's null within the finally block in your sample code, so that's fine.

It's not clear why you're not just using a using statement though. You can always put a try/catch inside (or outside) that.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值