【发布时间】:2014-07-31 22:02:30
【问题描述】:
首先我想明确一点,我一直在互联网上寻找解决我问题的方法,我找到的都是经典的
if(connection.open) return true;
在我的情况下无法满足我的需求的解决方案。
我正在开发一个应用程序。在它运行之前,我需要检查与 MySQL 数据库的连接,如果连接未完成,则会打开一个新窗口,提示用户进行连接设置(用户名、服务器地址、密码......)。在这个窗口我有一个测试连接按钮,看看连接是否建立,这是button_click事件的代码:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ApplicationSettings applicationSettings = new ApplicationSettings();
applicationSettings.ServerDatabase = tbdbName.Text;
applicationSettings.ServerIp = tbServer.Text;
applicationSettings.ServerUserName = tbUsername.Text;
//applicationSettings.ServerPassword = pbPassword.SecurePassword;
applicationSettings.MakeConnectionString();
MySqlConnection connection = new MySqlConnection(applicationSettings.ConnectionString);
try
{
connection.Open();
MessageBox.Show(this, "connection string: "+applicationSettings.ConnectionString+"connection OK!", "OK !", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ee)
{
MessageBox.Show(this, "connection string : "+applicationSettings.ConnectionString+"error : " + ee.Message, "connection ERROOOOR", MessageBoxButton.OK,
MessageBoxImage.Error);
}
finally
{
if(connection.State == ConnectionState.Open)
connection.Close();
}
}
如果我只输入服务器地址“applicationSettings.ServerIp”并点击测试连接按钮,会显示messageBox OK,连接字符串为:
服务器=127.0.0.1;数据库=;密码=;
我想这完全合乎逻辑,但我需要测试是否建立了与数据库的连接,如果我用任何随机值填充登录文本框,则连接建立。
问题:如何使用它来测试是否与数据库建立了连接?
【问题讨论】: