/// <summary>
/// 数据库连接方法一
/// </summary>
public void ConnDataMethod1()
{
string conn1 = "Data Source=(local);Initial Catalog=Test;Integrated Security=True";
SqlConnection ConnStr1 = new SqlConnection(conn1);
SqlCommand CommStr1 = ConnStr1.CreateCommand();
CommStr1.CommandText = "select DemoValue from Demo where DemoId=1";
ConnStr1.Open();
string Result = (string)CommStr1.ExecuteScalar();
ConnStr1.Close();
Console.WriteLine(Result);
}
/// <summary>
/// 数据库连接方法二
/// </summary>
public void ConnDataMethod2()
{
SqlConnectionStringBuilder strBuilder = new SqlConnectionStringBuilder();
strBuilder.DataSource = "(local)";
strBuilder.InitialCatalog = "Test";
strBuilder.IntegratedSecurity = true;
using (SqlConnection strConn2 = new SqlConnection(strBuilder.ToString()))
{
try
{
strConn2.Open();
if (strConn2.State == System.Data.ConnectionState.Open)
{
Console.WriteLine("Connection is Success!");
Console.WriteLine("ConnectionString is used:"+strConn2.ConnectionString);
}
}
catch (Exception)
{
if (strConn2.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Connection is fail!");
Console.WriteLine("Connection is used:"+strConn2.ConnectionString);
}
}
}
}