I'm getting a "Unreachable code detected" message in Visual Studio at the point con.close() in my code below. Can you spot what I've done wrong?
private int chek1(String insert)
{
OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=d:\\sdb.mdb");
OleDbCommand com = new OleDbCommand("select count(*) from sn where sn='" + insert + "\'", con);
con.Open();
int po = (int)com.ExecuteScalar();
if (po > 0)
return 1;
else
return 0;
con.Close();
}
The function exits when you return 1 or 0 (when you return anything, but 1 or 0 in your case); so there's no way that con.Close() can be called.
In the code you've posted, you're guaranteed to return, since you have a return statement in both branches of your if-statement. If only one branch had a return statement, con.Close() could still be reached.
But you shouldn't be using Close that way anyway -- you should be using using statements.
using (OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=d:\\sdb.mdb"))
using (OleDbCommand com = new OleDbCommand("select count(*) from sn where sn='" + insert + "\'", con))
{
con.Open();
int po = (int)com.ExecuteScalar();
if (po > 0)
return 1;
else
return 0;
// con.Close and con.Dispose will be called automatically at the end of the using block
}
Your code could be like this:
private int check(string sn)
{
using (OleDbConnection connection = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=d:\\sdb.mdb"))
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM sn WHERE sn=?";
command.Parameters.Add("@sn", sn));
con.Open();
return ((int)com.ExecuteScalar() > 0) ? 1 : 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With