首先我想明确的是,我一直在互联网上寻找解决我问题的方法,而我找到的都是经典的
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”并单击测试连接按钮,则会显示消息框“OK”,连接字符串为:
Server=127.0.0.1;Database=;Password=;
我想这是完全合乎逻辑的,但我需要测试是否建立了与数据库的连接,而且如果我用任何随机值填充登录文本框,则建立了连接。
问题:我如何使用它来测试是否与数据库建立了连接?
最佳答案
连接到数据库,发出一个简单的查询,如 SELECT 1 from <KnownTable>
并确保您成功收到返回的“1”。这确认您已经
- 已连接到物理服务器(无网络问题)
- 已通过数据库服务器进行身份验证(数据库正在运行并且您拥有正确的凭据)
- 连接到正确的数据库
关于c# - 如何在.NET应用程序中正确检查与mysql的数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25069681/