微软自己写的~测试远程数据库是否工作正常

本文提供了一段使用 C# 和 SQL Server 的 ADO.NET 进行数据库连接测试的代码示例。该示例首先定义了数据库连接字符串,并尝试打开连接,通过查询系统表来验证连接是否成功。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 <%@ Page Language= " C# " %>
 2 
 3 <%@ Import Namespace="System.Data.SqlClient" %>
 4 <%        
 5     string ServerName = "测试";
 6     string DBIP = "-"; // - 表示没有数据库服务器
 7     string DBName = "";
 8     string DBUser = "";
 9     string DBPassword = "";
10     string conn = string.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;
11                          User Instance=False;User ID={2};Password={3};MultipleActiveResultSets=true"
12        , DBIP
13        , DBName
14        , DBUser
15        , DBPassword);
16 
17 
18     string message = "NoSql";
19     if (DBIP != "-")
20     {
21         using (SqlConnection _conn = new SqlConnection(conn))
22         {
23             using (SqlCommand comm = new SqlCommand("SELECT COUNT(1)  FROM sys.tables", _conn))
24             {
25                 try
26                 {
27                     _conn.Open();
28                     comm.ExecuteReader();
29                     message = "OK";
30                     _conn.Close();
31                     _conn.Dispose();
32                 }
33                 catch (Exception)
34                 {
35                     message = "Fail";
36                 }
37 
38             }
39         }
40     }
41 
42 
43     string callback = Request["jsonpcallback"];
44     Response.ContentType = "application/x-javascript";
45     string str = callback + "({" + string.Format("\'ServerName\':\'{0}\', \'ServerIP\':\'{1}\',\'IISMessage\':\'{2}\',\'DBMessage\':\'{3}\'", ServerName, Request.ServerVariables["LOCAL_ADDR"].ToString(), "OK", message) + "})";
46     Response.Write(str);

 本文转自博客园张占岭(仓储大叔)的博客,原文链接:微软自己写的~测试远程数据库是否工作正常,如需转载请自行联系原博主。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值