![](/img/trans.png)
[英]C# nUnit test failing saying SQL Server CE constraint doesn't exist when it actually does
[英]c# breaking when sql view doesn't exist
我在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;
}
}
}
您可以捕獲SqlException,然后檢查特定的錯誤號:
catch (SqlException exSQL)
{
// want to check for number 10034 table or view doesn't exist
if (exSQL.Number == 10034)
{
this.lblPopMsg.Text = "view or table doesn't exist.";
}
}
要查看所有數字是什么,您可以在master數據庫上運行SQL查詢:
SELECT * FROM master.dbo.sysmessages
您可以對DB模式運行查詢以檢查視圖是否存在。 檢查此http://technet.microsoft.com/en-us/library/ms190324.aspx
您應該進行其他查詢,以查看該視圖是否存在,然后顯式處理該條件。
這是查詢以查看您的視圖是否存在:
select * from sys.views where name = 'AGENT_NAMES'
每當您查詢代理名稱時,我都不會這樣做,否則您將進行兩次數據庫調用。 只需在應用程序加載時執行一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.