我在 C# 中有这个函数,它应该从数据库视图中提取公司特定数据并在屏幕上显示该信息。如果出现错误,此函数中的 catch 语句将显示错误消息。如果我在其数据库上没有 AGENT_NAMES 视图的客户端服务器上运行此代码,该函数将显示以下错误:“此时无法建立连接”。相反,我希望该函数确定数据库中是否存在视图,如果不存在,则优雅地转义。我该怎么做呢?
编辑:正在使用的 DBMS 是 Microsoft SQL Server
private string getAgencyInfo()
{
string agentNo = null;
string agencyInfo = "";
try
{
agentNo = Session["Variable_AgencyID"].ToString();
}
catch
{
this.lblPopMsg.Text = "Connection timed out, Please Login";
this.ModalPopupExtender1.Show();
return agencyInfo;
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ARConnectionString"].ToString()))
{
try
{
cn.Open();
}
catch
{
clearLabels();
this.txtZipCode.Visible = false;
this.lblZipCode.Visible = false;
this.lblPopMsg.Text = "Unable to make a Connection at this Time";
this.ModalPopupExtender1.Show();
this.txtPolicyNo.Focus();
return agencyInfo;
}
try
{
string agentData = "SELECT AGENT_NAMES.NAME FROM AGENT_NAMES WHERE AGENT_NAMES.AGENT_NO = @agentNo";
SqlCommand command = new SqlCommand(agentData, cn);
command.Parameters.Add(new SqlParameter("agentNo", agentNo));
SqlDataReader dataReader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);
if (dataTable.Rows.Count != 0)
agencyInfo = dataTable.Rows[0][0].ToString() + " — Agent #" + agentNo;
return agencyInfo;
}
catch
{
clearLabels();
this.txtZipCode.Visible = false;
this.lblZipCode.Visible = false;
this.lblPopMsg.Text = "Unable to make a Connection at this Time";
this.ModalPopupExtender1.Show();
this.txtPolicyNo.Focus();
return agencyInfo;
}
}
}