在Visual Studio中使用MySQL并在运行时更改连接

时间:2014-06-10 19:46:02

标签: mysql .net visual-studio-2010 odbc

我在我的应用程序中使用这样的东西

MySqlConnection cnn = new MySqlConnection("Server=myServerAddress;" + 
                                          "Database=myDataBase;" + 
                                          "Uid=myUsername;" + 
                                          "Pwd=myPassword;");

每次都会改变,因为我们使用我们的应用程序部署数据库。 它工作正常。我输入using(new connection(cnn)){ query... }然后去。 我使用Windows ODBC数据管理员中定义的连接使用数据集。 但我很好奇,有没有办法使用我的本地测试数据库使用visual studio的数据集项,然后在运行时更改数据集的连接?更好的是,我可以使用c#以编程方式在运行时添加ODBC数据源吗?

3 个答案:

答案 0 :(得分:0)

通常从应用程序的同一文件夹中的应用程序exe.config文件加载连接字符串。可以使用项目属性中的“设置”选项卡定义此连接字符串。

  • 右键单击项目的属性
  • 选择“设置”选项卡(如果没有,请确认创建 设置)
  • 单击列类型中的ComboBox并选择Connection String
  • 为您的连接指定一个符号名称
  • 在“值”列中键入连接字符串(示例位于 connectionstrings.com

现在你的项目文件中你应该有app.config文件(变成yourapp.exe.config),其中有一个这样的部分

<configuration>
  <connectionStrings>
    <add name="MyAppConnection"
      connectionString="Server=myServerAddress;Database=myDB;Uid=user;Pwd=pass;" />
  </connectionStrings>
</configuration 

此时您使用

在程序中阅读
  string conString = ConfigurationManager
                        .ConnectionStrings["MyAppConnection"]
                        .ConnectionString;

相反,在动态情况下,您希望在运行时(从用户输入,您自己的配置文件等)自己构建连接字符串,然后您可以利用MySqlConnectionStringBuilder类的功能

MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder();
msb.Server = "localhost";
msb.Port = 3306;
msb.UserID = "root";
msb.Password = "xxx";
msb.Database = "test";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);
cnn.Open();

当然,这些文字值可以用你自己的变量代替。 这个类的文档很难找到。最好的文档是Sql Server equivalent之一。有趣的是,您可以从配置文件中读取静态连接字符串,然后仅更改所需的属性。

string conString = ConfigurationManager
                  .ConnectionStrings["MyAppConnection"]
                  .ConnectionString;
MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(conString);
msb.Database = "AnotherDB";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);

答案 1 :(得分:0)

应用程序连接字符串不能在运行时更改。 可以更改用户设置。

假设您正在使用名为“ MyConnectionString”的应用程序设置属性,该属性包含整个应用程序的连接字符串。 在主Program类上,创建一个全局字符串:

internal static string Prconnstring;

创建并保存此settings.cs文件:

namespace MYSOLUTIONORPROJECTNAME.Properties
{
    // (Not sure where I found this solution some time ago)
    // This class allows you to handle specific events on the settings class:
    //  The SettingChanging event is raised before a setting's value is changed.
    //  The PropertyChanged event is raised after a setting's value is changed.
    //  The SettingsLoaded event is raised after the setting values are loaded.
    //  The SettingsSaving event is raised before the setting values are saved.
    internal sealed partial class Settings
    {

        public Settings()
        {
            // // To add event handlers for saving and changing settings, uncomment the lines below:
            //
            // this.SettingChanging += this.SettingChangingEventHandler;
            //
            // this.SettingsSaving += this.SettingsSavingEventHandler;
            //
        }

        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
        {
            // Add code to handle the SettingChangingEvent event here.
        }

        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Add code to handle the SettingsSaving event here.
        }

        public override object this[string propertyName]
        {
            get
            {
                if (propertyName == "MyConnectionString")
                {
                    return Program.Prconnstring;
                }
                else
                {
                    return base[propertyName];
                }
            }
            set
            {
                base[propertyName] = value;
            }
        }
    }
}

在调用打开任何使用连接字符串的对象之前(例如,使用数据集的Form或使用在开发环境中创建的数据集的其他类的示例),您会以自己认为的任何方式创建新的连接字符串。 (示例:您可能想在当前用户的连接字符串中用作用户名。使用环境提供的信息创建连接字符串。

Program.Prconnstring = thenewruntime连接字符串。

现在,无论何时应用程序尝试获取MyConnectionString(在myapplicationname.config中进行了硬编码,并且无法更改),而是获取了您提供给thenewruntimeconnectionstring的新Program.Prconnstring。 / p>

请注意,开发连接字符串将是最终用户可见的,因为它只是一个文本文件。如果不希望这样做,则可以在部署过程中更改该文件(名为NAMEOFMYAPPLICATION.exe.config的文件),因为在那里硬编码的连接字符串对于运行中的应用程序无用。不要删除它,只需更改即可。

答案 2 :(得分:0)

您的连接字符串将存储在您的 App.config(或 C# 等效项)中。假设它叫做 MyConnectionString。只需将 My.Settings("MyConnectionString")="[your new connection string]" 添加到您的入口点即可在运行时更改为数据库绑定。例如:

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    My.Settings("MyConnectionString") = "server=remotedb.uk;user id=MainUser;password=2jdi38edhnche73g;database=mainDb;persistsecurityinfo=True;allowuservariables=True;defaultcommandtimeout=480;characterset=utf8mb4"

End Sub