如何操作SQL连接字符串

发布于 2024-09-05 10:17:28 字数 61 浏览 1 评论 0原文

我正在尝试操作 SQL 连接字符串,因此它不是运行数据库的原始副本,而是从 C# 项目中的副本文件夹中运行。

I'm trying to manipulate the SQL connection string so instead of running the original copy of our database it runs from the copy one folder up in our C# project.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

骄傲 2024-09-12 10:17:28

DbConnectionStringBuilder 类是一个很好的方法操作连接字符串的各种键/值对。您应该使用相关提供商特定的connectionstringbuilder 类。

The DbConnectionStringBuilder class is a nice way to manipulate various key/value pairs of a connection string. You should use the relevant provider specific connectionstringbuilder class.

酷到爆炸 2024-09-12 10:17:28

尝试看看这个:
http://msdn.microsoft.com/en- us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx

如果您使用 SQL Server,它比尝试操作字符串要好得多...

Try look at this:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx

If you use SQL Server it's much better than trying to manipulate a string...

神经大条 2024-09-12 10:17:28

最简单的方法可能是不按原样存储连接字符串,而是为要替换为不同值的位添加占位符。如果您使用 {0}{1} 等,则可以仅使用 string.Format 在运行时插入正确的值。

The easiest way would probably be that instead of storing the connectionstring as is, put in placeholders for the bits you want to replace with different values. If you use {0}, {1} etc, you could then just use string.Format to insert the correct values during runtime.

夏日浅笑〃 2024-09-12 10:17:28

我不能 100% 确定您的问题的背景是什么,但以下内容可能对您有用。
一种方法是让 App.Config 完成工作:

<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
<dataConfiguration defaultDatabase="DEV" />
<connectionStrings>
    <add name="DEV" connectionString="Database=xxx;Server=xxx;Trusted_Connection=True" providerName="System.Data.SqlClient" />
    <add name="LIVE" connectionString="Database=xxx;Server=xxx;Trusted_Connection=True" providerName="System.Data.SqlClient" />
</connectionStrings>...

然后您可以使用以下代码获取默认连接字符串(您可能希望将其放在一个单独的类中,以便可以在整个代码中使用它)。

    public static string DefaultDatabase
    {
        get
        {
            SystemConfigurationSource scs = new SystemConfigurationSource();
            return DatabaseSettings.GetDatabaseSettings(scs).DefaultDatabase;
        }
    }

    public static string DefaultConnectionString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings[Sql.DefaultDatabase].ConnectionString;
        }
    }

I'm not 100% sure what the context of your problem is but the following might work for you.
One way would be to let the App.Config do the work:

<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
<dataConfiguration defaultDatabase="DEV" />
<connectionStrings>
    <add name="DEV" connectionString="Database=xxx;Server=xxx;Trusted_Connection=True" providerName="System.Data.SqlClient" />
    <add name="LIVE" connectionString="Database=xxx;Server=xxx;Trusted_Connection=True" providerName="System.Data.SqlClient" />
</connectionStrings>...

You can then get the default connection string using the following code (which you might want to put in a separate class so you can use it throughout your code).

    public static string DefaultDatabase
    {
        get
        {
            SystemConfigurationSource scs = new SystemConfigurationSource();
            return DatabaseSettings.GetDatabaseSettings(scs).DefaultDatabase;
        }
    }

    public static string DefaultConnectionString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings[Sql.DefaultDatabase].ConnectionString;
        }
    }
小猫一只 2024-09-12 10:17:28

如果您使用 xsds/adapters,则需要在应用程序启动时手动设置适配器的连接字符串。如果您的适配器位于单独的库中,则需要使用可以向其传递 ConnectionString 的签名来重载适配器的构造函数(如果是这种情况,请阅读下文)。您用于创建 xsd 的首次连接字符串已被缓存。

如果是这种情况,请执行以下操作:

假设您有 User.xsd。右键单击然后查看代码。如果展开 (+) xsd,您会注意到 User.cs 已创建。

您可能生成了以下代码:

namespace Adapters {


    public partial class User
    {
    }
}

您应该添加以下内容:

namespace Adapters.UserTableAdapters
{
    public partial class UsersTableAdapter : global::System.ComponentModel.Component
    {
        public UsersTableAdapter(string connectionString)
        {
            this._clearBeforeFill = true;
            this._connection = new System.Data.SqlClient.SqlConnection();
            this._connection.ConnectionString = connectionString;
        }
    }
}

现在,当您初始化 UsersTableAdapter 时,您将 connectionString 传递给它。

因为我在整个网站上都使用了connectionString,而且不断阅读web.config 很烦人,所以我创建了这个简单的类:

namespace Data
{
    public class DataModule
    {
        private static string _connectionString = String.Empty;


        public static string ConnectionString
        {
            get
            {
                if (_connectionString == String.Empty)
                    throw new Exception("DataModule not initialized");
                return _connectionString;
            }
        }

        public static void initialize(string connectionString)
        {
            _connectionString = connectionString;
        }
    }
}

在ApplicationStart 上,我调用

DataModule.Initialize(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

注意,该类仅支持1 个connectionString。您可以轻松修改它以支持许多。

如果您更好地描述您的环境,我们可以为您提供更多帮助 =)

If you're using xsds/adapters, you'll need to set the connectionString of the adapter manually on application start. If you have your adapters in a separate library you need to overload the adapter's constructor with a signature to which you can pass a connectionString (read below if this is the case). The first-time connectionString you used to create an xsd is cached.

If this is the case, do the following:

Let's say you have User.xsd. Right click then view code. You'll notice User.cs is created if you expand (+) the xsd.

You might have this code generated:

namespace Adapters {


    public partial class User
    {
    }
}

You should add the following:

namespace Adapters.UserTableAdapters
{
    public partial class UsersTableAdapter : global::System.ComponentModel.Component
    {
        public UsersTableAdapter(string connectionString)
        {
            this._clearBeforeFill = true;
            this._connection = new System.Data.SqlClient.SqlConnection();
            this._connection.ConnectionString = connectionString;
        }
    }
}

Now, when you're initializing UsersTableAdapter, you pass the connectionString to it.

Because I use the connectionString all over the website and it's annoying to keep reading web.config for it, I created this simple class:

namespace Data
{
    public class DataModule
    {
        private static string _connectionString = String.Empty;


        public static string ConnectionString
        {
            get
            {
                if (_connectionString == String.Empty)
                    throw new Exception("DataModule not initialized");
                return _connectionString;
            }
        }

        public static void initialize(string connectionString)
        {
            _connectionString = connectionString;
        }
    }
}

On ApplicationStart, I call

DataModule.Initialize(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Note that this class supports only 1 connectionString. You can easily modify it to support many.

We can help you more if you describe your environment better =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文