如果有如下的方法:
public static DataSet GetInfo()
{
DataSet ds = new DataSet();
string sqlCode = @"Select xx From Table Where xx";
string connectionString = "xxxxxxxxxxxxxxxxx"; using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sqlCode, conn);
cmd.CommandTimeout = 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds); if (ds != null && ds.Tables.Count > 0)
return ds;
else
return null;
}
}
在使用SqlDataAdapter时,不必像SqlDataReader那样需要显示的指定 SqlConnection为Open状态,请问,在用SqlDataAdapter时,数据库连接会打开吗?
如果我加上 conn.Open() 和 conn.Close(),效率会比上面的代码要低吗?加和不加有什么区别?
public static DataSet GetInfo()
{
DataSet ds = new DataSet();
string sqlCode = @"Select xx From Table Where xx";
string connectionString = "xxxxxxxxxxxxxxxxx"; using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sqlCode, conn);
cmd.CommandTimeout = 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds); if (ds != null && ds.Tables.Count > 0)
return ds;
else
return null;
}
}
在使用SqlDataAdapter时,不必像SqlDataReader那样需要显示的指定 SqlConnection为Open状态,请问,在用SqlDataAdapter时,数据库连接会打开吗?
如果我加上 conn.Open() 和 conn.Close(),效率会比上面的代码要低吗?加和不加有什么区别?
try
{SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(sqlCode, conn);
cmd.CommandTimeout = 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
}
catch
{
throw;
}
fanily
{
if(conn的状态 是否打开 ) 如果打开 关闭
}我不知道我这样写和他那样在效率上有多大的差别
它会自动处理
不用using的话就要加上了
我在using块里面用SqlDataReader的话,还是需要显式指定 SqlConnection.Open(),不然就会报错。
请问,在用SqlDataAdapter时,数据库连接会打开吗?
如果我加上 conn.Open() 和 conn.Close(),效率会比上面的代码要低吗?加和不加有什么区别?
---
首先说说using的使用
他的作用是确保实现了IDispose接口的对象在出块以后自动释放资源,就相当于自动SqlConnection.close()
但是还得open(),可以任务这是托管型代码的一个特点,使用垃圾收集器---
接着说说SqlDataAdapter
使用他时不用自己手动打开和关闭连接,他有四个属性,对应四种操作,select insert update delete
我们可以为这个四个属性添加响应的操作,以完成批量插入,更新,删除
用了using可以不些close(),但良好的习惯是写
一般用来释放数据库连接资源。
当然conn.Open() 和 conn.Close()手写也是可以的
if(conn.state==connectionstate.open) conn.close();
否则可能会出错.