ADO.NET连接数据库(例:窗体上有4个文本框,一个连接按钮,提示数据库连接)

来源:互联网 发布:安广网络池州分公司 编辑:程序博客网 时间:2024/06/14 01:32
public string str;
        private void btnConnect_Click(object sender, EventArgs e)         //按钮单击事件
        {
            try                                                 //try....catch捕获异常
            {
                str = @"server=" + txtA.Text + ";" + "database=" + txtB.Text + ";" + "uid=" + txtC.Text + ";" + "pwd=" + txtD.Text;     //获取四个文本框中的
                SqlConnection cnn = new SqlConnection();     //实例化SqlConnection

                cnn.ConnectionString = str;          //连接数据库                

                 cnn.Open();              //打开数据库

                if (cnn.State == ConnectionState.Open)        //如果数据库的状态是打开的
                {
                    MessageBox.Show("数据库已经打开", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库没有打开", "提示");


            }
            
                
        }
0 0
原创粉丝点击