首页 > 代码库 > Ado.net的初步链接

Ado.net的初步链接

            string connStr = "Data Source=.;Initial Catalog=MySchoolMoreData;Integrated Security=True";
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    //打开连接
                    conn.Open();
                    MessageBox.Show("ok");
                    //conn.Close();
                    conn.Dispose(); //没用释放只是清空了连接字符串
                    conn.ConnectionString = connStr;
                    conn.Open();
                    MessageBox.Show("ok2"); 
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnPool_Click(object sender, EventArgs e)
        {
            
            string connStr = "Data Source=.;Initial Catalog=MySchoolMoreData;Integrated Security=True;pooling=false"; //0,2   2.9    6.0  9
            string sql = "select * from grade";
            Stopwatch sw = new Stopwatch();//创建一个秒表
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    //SqlConnection conn = new SqlConnection(connStr);
                    SqlCommand comm = new SqlCommand(sql, conn);
                    comm.ExecuteScalar();
                    conn.Close(); 
                }
                //SqlConnection conn = new SqlConnection(connStr);
            }
            sw.Stop();
            MessageBox.Show(sw.Elapsed.ToString());
        }

        private void btnState_Click(object sender, EventArgs e)
        {
            string connStr = "Data Source=.;Initial Catalog=MySchoolMoreData;Integrated Security=True;pooling=false";
            SqlConnection conn = new SqlConnection(connStr);
            conn.StateChange += Change;
            conn.Open();
            conn.Close();
        }

        void Change(object sender, StateChangeEventArgs e)
        {
            MessageBox.Show(e.OriginalState+"   "+e.CurrentState);
        }

        private void btnGetId_Click(object sender, EventArgs e)
        {
            string connStr = "Data Source=.;Initial Catalog=MySchoolMoreData;Integrated Security=True;pooling=false";
            using(SqlConnection conn=new SqlConnection(connStr))
            {
                conn.Open();
                //string sql = "insert into grade values(‘" + txtName.Text.Trim() + "‘);select @@identity";
                string sql = " insert into grade output inserted.classid values(‘" + txtName.Text.Trim() + "‘)";
                //方法的意义不在于执行那一些命令,而在于能够接收到某种操作类型的返回值
                SqlCommand command = new SqlCommand(sql, conn);
                //调用什么方法,由你那一种类型的返回值决定
                int obj =Convert.ToInt32(command.ExecuteScalar());
                MessageBox.Show("标识列值是:"+obj);
            }
        }
    }