class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection(); //1.手写 //string connStr = "server=.;database=db1;uid=sa;pwd=123"; //2.SqlConnectionStringBuilder生成连接字符串 //SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(); //connStrBuilder.DataSource = ".";//设置数据源 //connStrBuilder.InitialCatalog = "db1";//数据库名 //connStrBuilder.UserID = "sa";//账号 //connStrBuilder.Password = "123";//密码 //connStrBuilder.Pooling = false;//禁用连接池 //string connStr = connStrBuilder.ConnectionString; //3.读取配置文件里的连接字符串 //3.1 //string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;//读取连接字符串 //3.2 string connStr = ConfigurationManager.AppSettings["connStr"].ToString(); //连接字符串如果任何一个元素设置不正确,都不能正常打开conn conn.ConnectionString = connStr; conn.Open(); conn.Close(); } }