C# SqlCommand 的问题??

来源:百度知道 编辑:UC知道 时间:2024/05/29 09:50:29
SqlCommand comm = new SqlCommand(sql_string,sqlConnection);
和comm.CommandText=sql_string;comm.Connection = sqlConnection;两者使用起来有什么区别吗??拜托了。。

当然有区别,
SqlCommand comm = new SqlCommand(sql_string,sqlConnection);
这句是告诉程序,用的是哪个数据库连接(sqlConnection),数据库语句是什么(sql_string).不改sql_string的情况下,他只执行你第一次写的sql_string语句。connection类似。

comm.CommandText=sql_string;
comm.Connection = sqlConnection;
这2句是用来更改语句和连接的,前提是你已经new了一个SqlCommand的对象comm.没有new的情况下这2句没意义。这2句语句只是在不销毁SqlCommand对象的情况下,更换数据库连接和sql语句,对象依然是那个对象。

如果你只使用SqlCommand comm = new SqlCommand(sql_string,sqlConnection);
那么每次的comm 都是一个新的comm 。
希望你能理解

效果上没有区别
不过,第二段是:
SqlCommand comm = new SqlCommand(); // 你少了这句
comm.CommandText=sql_string;
comm.Connection = sqlConnection;

区别是new SqlCommand(); 时没有指定sql和数据库连接,要在后面手动指定
而new SqlCommand(sql_string,sqlConnection); 则直接在构造函数里指定了

我一般用这种的比较多
SqlCommand comm = new SqlCommand(sql_string,sqlConnection);
但是如上面说的,每次都新建一个comm,必须每次执行完,都要及时的将其关闭,不然会导致内存泄漏,可能还是下面一种好点,只需要在页面的开始建立一个conn,在页面的中间可以多次使用comm.CommandText=sql_string;comm.Connection = sqlCo