创建新的SqlCommand的或重复使用的同一个 [英] Create new SQLCommand's or reuse the same one

查看:552
本文介绍了创建新的SqlCommand的或重复使用的同一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用ADO.NET,要执行一前一后的命令列表发送到SQL 2008。我要创造,我要送每个SQL一个新的SqlCommand? 或者重复使用相同的SqlCommand,只是改变CommandText属性? 谢谢,内斯特

I need to send a list of commands to SQL 2008 using ADO.NET, to be executed one after the other. Should I create a new SQLCommand for each SQL that I'm sending? Or reuse the same SQLCommand and just change the CommandText property? Thanks, Nestor

推荐答案

SqlCommands是pretty的轻量。你是安全的,每次创建一个新的。

SqlCommands are pretty light-weight. You are safe to create a new one each time.

有并发症,你需要清除,并重置所有参数,在这一点上参数化的命令,创建一个新的命令是干净的,易于理解,有效的。

There are complications with parametrized commands where you need to clear and reset all parameters, and at that point, creating a new command is clean, easy to understand, and effective.

在此外,它通常是行每次使用一个新的SqlConnection为好。自动,内置的连接池是神奇,使这种高效的。

In addition, it is usually OK to use a new SqlConnection each time as well. The automatic, built-in connection pooling is the "magic" that makes this efficient.

我用这样的:

public void ExecuteQuery(string query)
{
    this.ExecuteQuery(query, null);
}

public void ExecuteQuery(string query, Dictionary<string, object> parameters)
{
    using (SqlConnection conn = new SqlConnection(this.connectionString))
    {
        conn.Open();

        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = query;

            if (parameters != null)
            {
                foreach (string parameter in parameters.Keys)
                {
                    cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
                }
            }

            cmd.ExecuteNonQuery();
        }
    }
}

这篇关于创建新的SqlCommand的或重复使用的同一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆