使用连接的时候推荐使用下面的模式来处理连接:
string source = "server=(local);" + " integrated security = SSPI;" + " database = Students";
try
{
using (SqlConnection conn = new SqlConnection(source))
{
// Open the connenction
conn.Open();
// Do something useful
// Close the connection
conn.Close();
}
}
catch(SqlException ex)
{
// Log the exception
}
这样可以确保资源得到有效释放,不至于导致SQL可能出现的表会被锁住不能访问的情况。