我正在尝试创建一个if语句,以防我无法打开与SQL Server的连接,显示标签,或者显示另一个表单。代码如下:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=xxx.ac.uk;Initial Catalog=XXXX;User ID=xxxx;Password=xxxxx");
try
{
// string sql = "SELECT * FROM datatable";
SqlCommand mycommand = new SqlCommand("SELECT * FROM datatable", conn);
try
{
conn.Open();
mycommand.ExecuteNonQuery();
}
finally
{
if (mycommand != null)
label1.Visible = true;
label1.Text = "Failed to Access Database! Please log into VPN Using The Link Below.";
}
}
finally
{
if (conn != null)
this.Hide();
Form1 form = new Form1();
form.Show();
}
}
}
}
每当我离线运行文件时,都会出现超时问题,因为我收到异常,我无法使用该应用程序。我想要if语句检查是否有连接然后转到表单,如果没有,则显示标签。
此致,任何帮助表示赞赏。
答案 0 :(得分:1)
我认为你的方法试图做得太多了。您不必查询表。只需打开连接即可。
var canAccessDB = false;
try
{
conn.Open();
canAccessDB = true; // Will only get here if Open() is successful
}
catch
{
// nothing needed here
}
finally
{
if (conn != null)
conn.Dispose(); // Safely clean up conn
}
if (!canAccessDB)
{
label1.Visible = true;
label1.Text = "Failed to Access Database! Please log into VPN Using The Link Below.";
}
else
{
this.Hide();
}
Form1 form = new Form1();
form.Show();
答案 1 :(得分:0)
每次都会运行finally块。如果try块中有什么问题,你需要一个带代码的catch块来执行。
答案 2 :(得分:0)
如果连接失败并且向用户显示消息
,您可以捕获SqlExceptionusing (SqlCommand mycommand = new SqlCommand("SELECT * FROM datatable", conn))
{
try
{
conn.Open();
mycommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
label1.Visible = true;
label1.Text = string.Format("Failed to Access Database! Please log into VPN Using The Link Below.\r\n\r\nError: {0}", ex.Message);
return;
}
if (conn != null)
{
this.Hide();
Form1 form = new Form1();
form.Show();
}
}