我在C#中有這個功能,它應該從數據庫視圖中提取公司特定的數據並在屏幕上顯示該信息。如果出現錯誤,此函數中的catch語句將顯示錯誤彈出消息。如果我在其數據庫上沒有AGENT_NAMES視圖的客戶端服務器上運行此代碼,該函數將顯示以下錯誤:「無法在此時進行連接」。我反而喜歡該函數來確定視圖是否存在於數據庫中,如果不存在,則優雅地轉義。我該怎麼做呢?c#打破sql視圖不存在時
編輯:正在使用的數據庫管理系統爲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;
}
}
}
您獲得查詢相關數據庫的系統表的權限,然後編寫查找該視圖的查詢。細節取決於RDBMS,這是你未能指定的。或者,您可以使用從.net獲取的異常對象來查看是否有任何有用的信息。 –