ASP.NET数据库连接字符串写在config.web配置文件中时间:2022-09-22 07:27:28方法一: //1 在web.config的conafiguration里面添加<configuration> <appSettings> <add key="SqlConString" value="server=diablota;database=dbmessage;uid=sa;pwd="/> </appSettings> <connectionStrings/>//2 新建类库Data.cs里面的SqlConString静态私有属性读取配置文件using System.Configuration; public class Data { private Data() { } public static string SqlConString { get { return ConfigurationManager.AppSettings["SqlConString"]; } } }//3 实例化的时候调用,静态方法直接调用SqlConnection sqlcon = new SqlConnection(Data.SqlConString) 方法二: //1 在web.config中添加配置信息<configuration><connectionStrings><add name="conStr" connectionString="server=localhost;database=master;uid=sa;pwd="/></connectionStrings></configuration>//2 添加引用//引用程序集添加引用->选.Net下的->System.configuration//导入命名空间System.Configuration //3 获取连接字符串public static string GetConStr(){//读取配置文件的字符串ConnectionStringSetting setting = ConfigurationManager.ConnectionStrings["conStr"]//或者ConfigurationManager.ConnectionStrings["constr"].ConnectionString;}