用SqlConnectionStringBuilder生成数据库连接字符串

《使用SqlConnection类连接数据库方法》

//引入命名空间

using System.Data.SqlClient;

   protected void Button1_Click(object sender, EventArgs e)
    {
        //ConnectionString定义了连接字符串
        string ConnectionString = "Data Source=. ; Initial Catalog=Pubs; User ID=sa";
        //使用连接字符串构造一个SqlConnection实例
        SqlConnection conn = new SqlConnection(ConnectionString);
        try
        {
            //打开连接
            conn.Open();
            //如果当前状态打开,在控制台输出
            if (conn.State == ConnectionState.Open)
            {
                Label1.Text = "当前数据库已经连接!<br/>";
                Label1.Text += "连接字符串为:" + conn.ConnectionString;
            }
        }
        catch (SqlException ex)
        {
            Label1.Text = "当前数据库已经失败!<br/>";
            Label1.Text += "失败的原因是:" + ex.Message;
        }
        finally
        {
            //调用Close方法即使关闭连接
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }

 

《使用SqlConnectionStringBuilder连接字符串方法》

//引入命名空间

using System.Data.SqlClient;

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnectionStringBuilder connBuider = new SqlConnectionStringBuilder();
        //DataSource表示数据源位置,可以是IP地址,也可以指定一个DNS名称
        connBuider.DataSource = ".";
        //InitialCataLog指定需要连接数据库的名称
        connBuider.InitialCatalog = "Pubs";
        //IntegratedSecurity表示是否使用整合身份验证进行登录数据库
        connBuider.IntegratedSecurity = false;
        //不使用整合Windows身份验证时,指定用户ID和密码
        connBuider.UserID = "sa";
        connBuider.Password = "";

        //使用SqlConnetionStringBuilder.ToString()方法将会输出连接字符串
        using(SqlConnection conn=new SqlConnection(connBuider.ToString()))
            try
            {
                //打开连接
                conn.Open();
                //如果当前状态打开,在控制台输出
                if (conn.State == ConnectionState.Open)
                {
                    Label1.Text = "当前数据库已经连接!<br/>";
                    Label1.Text += "连接字符串为:" + conn.ConnectionString;
                }
            }
            catch (SqlException ex)
            {
                Label1.Text = "当前数据库已经失败!<br/>";
                Label1.Text += "失败的原因是:" + ex.Message;
            }
            finally
            {
                //调用Close方法即使关闭连接
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值