gpt4 book ai didi

c# - 如何检查连接字符串是否有效?

转载 作者:行者123 更新时间:2023-11-30 18:49:44 25 4
gpt4 key购买 nike

我必须保存数据并且必须在保存之前测试连接。如何测试此连接字符串对特定连接是否有效?

我的代码是这样的:

static public bool TestConnString(string connectionString)
{
bool returnVal = true;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();

if (conn.State != ConnectionState.Open)
returnVal = false;
else
returnVal = true;
}
catch (Exception ex)
{
returnVal = false;
}
}

return returnVal;
}

连接字符串是:

Data Source=testSvr03\SQLEXPRESS;Initial Catalog=Test; Connection Timeout=600; Persist Security Info=True;User ID=Test; password=test 

如果我在连接字符串中提供了错误的数据源,那么它永远不会在 conn.open() 之后在此函数中返回。我放置了 catch block ,但它正在进入它

谁能告诉我什么是解决方案?

最佳答案

你可以让 SqlConnectionStringBuilder构造函数检查它:

bool isValidConnectionString = true;
try{
var con = new SqlConnectionStringBuilder("ABC");
}catch(Exception)
{
// can be KeyNotFoundException, FormatException, ArgumentException
isValidConnectionString = false;
}

Here's an overview不同数据提供者的ConnectionStringBuilders:

Provider                   ConnectionStringBuilder 
System.Data.SqlClient System.Data.SqlClient.SqlConnectionStringBuilder
System.Data.OleDb System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.Odbc System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OracleClient System.Data.OracleClient.OracleConnectionStringBuilder

关于c# - 如何检查连接字符串是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com