ADO.NET数据库的连接(SQL数据库的连接)

来源:互联网 发布:什么电脑壁纸软件好 编辑:程序博客网 时间:2024/05/03 08:03

定义一个类  DBclass:

 public bool OpenSQLServer()
        { 
             string str=@"server=.\sqlexpress;database=stuInfo111;uid=sa;pwd=yy199455";  
            SqlConnection cnn=new SqlConnection();  //创建一个SqlConnection的实例
            cnn.ConnectionString=str;   //数据库的连接
            cnn.Open();    //打开数据库
            if(cnn.State==ConnectionState.Open)  //如果数据库的状态是打开的
            {
               return true;
            }
            else 
            {
               return false;
            }
        }


定义一个按钮,单击按钮时打开数据库:

 private void button1_Click(object sender, EventArgs e)
        {
            DBclass db = new DBclass();
            if (db.OpenSQLServer())
            {
                MessageBox.Show("数据库已经打开", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("数据库没有打开", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

0 0
原创粉丝点击