Reputation: 121
The following code checks if I can connect to the MySQL database or not. It is working fine when it connects but when it can't connect it throws out an error instead of executing the 'Else' statement
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQLConnection
{
public partial class FrmConnection : Form
{
public FrmConnection()
{
InitializeComponent();
}
string connectionString = "host=192.168.0.91; database=c#1; user=test1; password=test1";
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection con= new MySqlConnection(connectionString))
{
con.Open();
if(con.State==ConnectionState.Open)
{
label1.Text = "Connection Established!";
}
else
{
label1.Text = "Connection Error!";
}
}
}
}
}
I get this error
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Unable to connect to any of the specified MySQL hosts.
Upvotes: 0
Views: 7968
Reputation: 14982
To handle exceptions, you can do this:
using (MySqlConnection con= new MySqlConnection(connectionString))
{
try
{
con.Open();
label1.Text = "Connection Established!";
}
catch(Exception ex)
{
label1.Text = "Connection Error!\n"+ex.Message;
}
finally
{
con.Close();
}
}
It's pretty explained: It will try
to open the connection and set a success message.
If it fails, it will say that the connection failed and display the error message from the catched
exception.
Then, on the finally
block, it will close the connection, after both try
and catch
has finished executing.
I'm not sure but since you're using using
, you wouldn't need the finally block, for the using
function will close the connection automatically.
More info on the MSDN page for the try catch finally
blocks.
Upvotes: 1