Asidy'Blog

学会感恩,学会共享;先做人,后做技术……
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP.NET2.0数据库连接方法总结一

Posted on 2007-12-03 00:10  Asidy  阅读(522)  评论(4编辑  收藏  举报

        /// <summary>
        /// 数据库连接方法一
        /// </summary>
        public void ConnDataMethod1()
        {
            string conn1 = "Data Source=(local);Initial Catalog=Test;Integrated Security=True";

            SqlConnection ConnStr1 = new SqlConnection(conn1);
            SqlCommand CommStr1 = ConnStr1.CreateCommand();
            CommStr1.CommandText = "select DemoValue from Demo where DemoId=1";
            ConnStr1.Open();
            string Result = (string)CommStr1.ExecuteScalar();
            ConnStr1.Close();
            Console.WriteLine(Result);
        }
        /// <summary>
        /// 数据库连接方法二
        /// </summary>
        public void ConnDataMethod2()
        {
            SqlConnectionStringBuilder strBuilder = new SqlConnectionStringBuilder();
            strBuilder.DataSource = "(local)";
            strBuilder.InitialCatalog = "Test";
            strBuilder.IntegratedSecurity = true;

            using (SqlConnection strConn2 = new SqlConnection(strBuilder.ToString()))
            {
                try
                {
                    strConn2.Open();
                    if (strConn2.State == System.Data.ConnectionState.Open)
                    {
                        Console.WriteLine("Connection is Success!");
                        Console.WriteLine("ConnectionString is used:"+strConn2.ConnectionString);
                    }
                }
                catch (Exception)
                {
                    if (strConn2.State != System.Data.ConnectionState.Open)
                    {
                        Console.WriteLine("Connection is fail!");
                        Console.WriteLine("Connection is used:"+strConn2.ConnectionString);
                    }
                }
            }
        }