CFIF 语句检查数据库 (MSSQL) 是否正在连接或存在

CFIF statement checking if database (MSSQL) is connecting or exists

我正在尝试在 Coldfusion 16 中编写一个 if 语句来检查它是否可以连接到数据库或者它是否存在。如果它可以连接到数据库,则显示该页面,否则显示该页面以进行维护。我应该如何检查以确保数据库已启动?如有任何帮助,我们将不胜感激。

<cfquery name="DBUP" datasource="datasource"> 
SELECT ID
FROM dbo.Entry 
</cfquery> 

<cfif DBUP>
 Show Page
<cfelse>
 Show Down For Maintenance
</cfif>

您可能需要在 Application.cfc onRequest 方法中添加它。

<cftry>
 <cfquery name="DBUP" datasource="datasource"> 
  SELECT ID
  FROM dbo.Entry 
  </cfquery>
<cfcatch type="any">
  Show DOwn For Maintenance
   <!---everything optional below this line--->
   <!---can show some custom message---> 
  <cfinclude template="errorMsg.cfm">
  <!---stop the processing further--->
  <cfabort>
</cfcatch> 
</cftry> 

您不应直接将错误消息或文件放入 catch 语句中。我们应该再检查一个条件,即)错误代码是否为 0。想象一下,在某些时候开发人员可能会给出错误的查询,例如未定义的列或缺少语法等......在那个时候也会执行 catch。因此,根据要求,我们必须检查数据源是否存在。如果我们想检查所有类型的问题意味着我们不需要错误代码条件。

<cftry>
        <cfset showPage = true>
        <cfquery name="DBUP" datasource="datasource">
            SELECT ID FROM dbo.Entry 
        </cfquery>
        <cfcatch type="database">
            <!--- The error code 0 is mentioned Datasource could not be found/exits.  --->
            <cfif cfcatch.cause.errorcode eq 0 >
              <cfset showPage = false >
                <!--- Data source does not exists --->
            </cfif>

        </cfcatch>
    </cftry>

基于 showPage 值,您在此处执行业务逻辑 .... .... ....