实现功能:
连接数据库(使用connection对象连接数据库DBS,点击“连接数据库”,使得程序与数据库进行连接(connection对象打开),点击“断开数据库”(connection对象关闭),在此过程中监测connection.State状态,并把连接状态显示在下方的Label中)
效果图如下:
代码如下:
//窗体Load事件
private void _4_1_Load(object sender, EventArgs e)
{
//更改控件的显示内容的颜色
groupBox1.ForeColor = Color.Blue;
button1.ForeColor = button2.ForeColor = SystemColors.ControlText;
label1.ForeColor = Color.Red;
}
//实例化对象,用于开启程序和数据库之间的连接
SqlConnection conn;
//“连接数据库”按钮的Click事件
private void button1_Click(object sender, EventArgs e)
{
//连接数据库
conn = new SqlConnection(@"Integrated Security=SSPI;
Persist Security Info=False;Initial Catalog=WinFormSQL;Data Source=localhost");
//打开数据库连接
conn.Open();
//数据库连接状态为打开时,label的内容显示“连接中...”
if (conn.State == ConnectionState.Open)
label1.Text = "连接中...";
}
//“断开数据库”按钮的Click事件
private void button2_Click(object sender, EventArgs e)
{
//关闭数据库连接
conn.Close();
//数据库连接状态为关闭时,label的内容显示“连接已关闭”
if (conn.State == ConnectionState.Closed)
label1.Text = "连接已关闭";
}
代码均为原创,存在不足还请见谅!如有转载请注明来源: www.dreamload.cn/blog/?p=441&preview=true (洋葱先生)