从SqlParameterCollection参数获取参数列表

时间:2015-09-16 15:12:57

标签: c# .net

如何获取传递给SqlParameterCollection Parameters的参数列表?有可能以某种方式枚举它们吗?

command.Connection = defaultConnection; 
command.CommandType = CommandType.Text;
command.CommandText =
    "INSERT into logs (ClientID, Msg, LogLevel, Date) VALUES (@ClientID, @Msg, @LogLevel, getdate())";
command.Parameters.AddWithValue("@ClientID", id);
command.Parameters.AddWithValue("@Msg", info);
command.Parameters.AddWithValue("@LogLevel", level);

现在我想从command.Parameters

获取参数作为文本

UPD:

string s="";

    foreach (var param in command.Parameters)
        {
        s=s+ param ;  //how to get parameter with it's name in string type ?
        }                          

2 个答案:

答案 0 :(得分:1)

创建SqlCommand对象时,

using (SqlCommand command = new SqlCommand(commandText, connection)) { command.CommandType = CommandType.StoredProcedure; connection.Open(); SqlCommandBuilder.DeriveParameters(command); //instead of command.Parameters.AddWithValue("@Param",value); command.Parameters["@Param"].Value = value; 为空。 SqlCommandBuilder.DeriveParameters(命令)能够连接到DB并填充Command.Parameters ,这样您就可以为每个参数设置所需的值。

<div class="container">
<div class="row">
            {% for projects in project %}
                <div class="col-md-4">
                    <li>
                        <a href="{{ current_page.get_absolute_url }}{{ project.slug }}">
                            <img src="{{ projects.main_image.image|thumbnail_url:'projects_top_thumbnail' }}" alt="{{ projects.title }}" />
                            <div class="showcase-title">
                                {{ projects.title }}
                            </div>
                        </a>
                    </li>                                
                </div>   
            {% endfor %}
</div>
            <div class="pagination">
            <span class="step-links">
                {% if project.has_previous %}
                    <a href="?page={{ project.previous_page_number }}">previous</a>
                {% endif %}

            <span class="current">
                Page {{ project.number }} of {{ project.paginator.num_pages }}.
            </span>

                {% if project.has_next %}
                    <a href="?page={{ project.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
</div>

答案 1 :(得分:1)

var s = string.Join(",", cmd.Parameters.Cast<SqlParameter>().ToList().Select(p => @"{p.ParameterName}={p.Value}"));