先创建一个连接函数
private static string GetConnectionString(ConnectionStringPattern pattern)
{
string connectionString = string.Empty;
switch (pattern)
{
case ConnectionStringPattern.ByString:
connectionString = "Data Source=.;Initial Catalog=MyDatebase;Integrated Security=True";
break;
case ConnectionStringPattern.BySqlConnectionStringBuilder:
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = ".";
sqlBuilder.InitialCatalog = "MyDatebase";
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "Hn1234";
connectionString = sqlBuilder.ConnectionString;
break;
case ConnectionStringPattern.ByConfiguration:
connectionString = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
break;
default:
throw new Exception("Pattern Error");
}
return connectionString;
}
上面可以按照sqlserver登录的不同模式返回登录的字符串
传入的参数为枚举变量
public enum ConnectionStringPattern
{
ByString,
BySqlConnectionStringBuilder,
ByConfiguration
}
调用的时候先创建一个 SqlConnection
然后把上面得到的值赋给SqlConnection.ConnectionString
代码如下
private static void GetAllName()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GetConnectionString(ConnectionStringPattern.BySqlConnectionStringBuilder);
conn.Open();
Console.WriteLine(conn.State.ToString());
string commandText = "select * from staff";
SqlCommand command = new SqlCommand(commandText, conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["name"]);
}
}
}
}
注:如果 添加using System.Configration还是找不到ConfigurationManager的话就在工程里面的reference里添加一下引用