这2段程序有区别吗?区别在哪里?

来源:百度知道 编辑:UC知道 时间:2024/06/25 03:04:37
程序段一:
SqlConnection conn=new SqlConnnection("...");
conn.Open();
SqlCommand cmd=new SqlCommand("...",conn);
int num=0;
for(int i=0;i<1000;i++)
num+=i;
cmd.ExecuteNonQuery();
conn.Close();
程序段二:
SqlConnection conn=new SqlConnnection("...");
SqlCommand cmd=new SqlCommand("...",conn);
int num=0;
for(int i=0;i<1000;i++)
num+=i;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

当然有区别
程序一比程序二,在打开数据库的时间上要长。原则上是尽量缩短数据库的打开时间。

有区别.
数据库连接这种对象比较"珍贵",因为每个SQL Server正版授权可以按照客户端连接数去购买.也就是说,你虽然买了个SQL Server,但是连接数也可能有限制.所以, 应用程序连接到数据库服务器尽量少数量, 且使用完成立刻关闭.

很明显, 前者先打开后执行循环1000次, 再关闭.占用了时间.后者则无.