asp.net 2.0 的数据库的连接类(通过配置文件读连接串)

时间:2022-03-31 13:15:37

/// dbcon 数据库的连接类,可调用静态函数创建
/// </summary>
///

    public class dbcon
    {
        public dbcon()
        {
        }

        public static SqlConnection createConnection()
        {

           //以下字串为初始值,读配置文件中内容后被替换
            string connStr= "server=(sql server IP地址);database=(数据库名称);uid=(用户名);pwd=(口令)";


           Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("~/");
           ConnectionStringSettings connString;

            if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
            {
                connString = rootWebConfig.ConnectionStrings.ConnectionStrings["DbConn"];
                if (null != connString)
                    connStr = connString.ConnectionString;
            }

            return new SqlConnection(connStr);
           
        }
    } 

 

配置文件

<?xml version="1.0"?>

<configuration>
 <appSettings>

 </appSettings>
 <connectionStrings>
  <add name="DbConn" connectionString="server=(sql server IP地址);database=(数据库名称);uid=(用户名);pwd=(口令)" providerName="System.Data.SqlClient"/>
 </connectionStrings>
……
</configuration>



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1513056