ConnectionState枚举
作用:用来监测某个Connection对象当前的状态
using System.Data.SqlClient;
SqlConnection con = new SqlConnection();
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = "Server=127.0.0.1;DataBase=InLettDB;UID=sa;Pwd=123;";
}
/// <summary>
/// 来测试当前应用程序是否能够连接到数据库
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text=="打开服务器")
{
con.Open();
if (con.State == ConnectionState.Open)
{
MessageBox.Show("成功连接到服务器");
button1.Text = "关闭服务器";
}
}
else if (button1.Text== "关闭服务器")
{
con.Close();
if (con.State== ConnectionState.Closed)
{
MessageBox.Show("与服务器断开连接");
button1.Text = "打开服务器";
}
}
}