连接超出作用域后不会自动关闭也不能由垃圾回收机制来释放必须手动关闭或释放该资源
5、连接sqlserver 实例
(1)使用windows认证
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace sqlconnection1
{
class Program
{
static void Main(string[] args)
{
string source = "Data Source=duanyf//SQLEXPRESS;" + "Initial Catalog=master;"+"Integrated Security=True";
SqlConnection con = new SqlConnection(source);
try
{
con.Open();
Console.WriteLine("connection is successful!");
}
catch (Exception e)
{
Console.WriteLine("connection error is :{0}", e.ToString());
}
Console.ReadLine();
con.Close();
}
}
}
(2)使用sqlserver认证
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace sqlconnection1
{
class Program
{
private void SQLConnectionF(string source)
{
SqlConnection con = new SqlConnection(source);
try
{
con.Open();
Console.WriteLine("connection is successful!");
}
catch (Exception e)
{
Console.WriteLine("connection error is :{0}", e.ToString());
}
}
static void Main(string[] args)
{
string sou = "server=duanyf//SQLEXPRESS;" + "Initial Catalog=master;" + "UID = sa;"+"Password = aaa";
Program sqlcon = new Program();
sqlcon.SQLConnectionF( sou);
Console.ReadLine();
//con.Close();
}
}
}
我是把代码复制过来的,在live writer中有点乱 也没法排,复制到visualstudio中就好了。