如何检查是否连接字符串是有效的? [英] How to check if connection string is valid?

查看:165
本文介绍了如何检查是否连接字符串是有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写其中一个用户提供手动连接字符串的应用程序,我想知道是否有什么办法,我可以验证连接字符串 - 我的意思是检查它是否是正确的,如果数据库中存在

I'm writing an application where a user provides a connection string manually and I'm wondering if there is any way that I could validate the connection string - I mean check if it's correct and if the database exists.

推荐答案

您可以尝试连接?为了快速(脱机)验证,或者使用 DbConnectionStringBuilder 来分析它...

You could try to connect? For quick (offline) validation, perhaps use DbConnectionStringBuilder to parse it...

    DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
    csb.ConnectionString = "rubb ish"; // throws

不过,检查数据库中是否存在,你需要尝试连接。最简单的,如果你知道供应商,当然是:

But to check whether the db exists, you'll need to try to connect. Simplest if you know the provider, of course:

    using(SqlConnection conn = new SqlConnection(cs)) {
        conn.Open(); // throws if invalid
    }

如果你只知道供应商作为一个字符串(在运行时),然后使用 DbProviderFactories

If you only know the provider as a string (at runtime), then use DbProviderFactories:

    string provider = "System.Data.SqlClient"; // for example
    DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
    using(DbConnection conn = factory.CreateConnection()) {
        conn.ConnectionString = cs;
        conn.Open();
    }

这篇关于如何检查是否连接字符串是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆