简体   繁体   English

在 asp.net 查询中处理 select 查询中的 SqlCommand null 参数

[英]Handling SqlCommand null parameters in a select query in asp.net

I have this example code:我有这个示例代码:

string query = "select * from xy where id == @id and name == @name";
SqlCommand cmd = new SqlCommand(query);
if(txtUsername.Text.Length > 0)
{
cmd.Parameters.Add["@name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = txtUsername.Text;
}

Now if the txtUsername <=0 I have to cut the query string dropping the AND and the name == @name.现在,如果 txtUsername <=0 我必须删除删除 AND 和名称 == @name 的查询字符串。 How can I achieve this result?我怎样才能达到这个结果?

Thanks in advance.提前致谢。

bool useName = !String.IsNullOrEmpty(txtUsername.Text);
StringBuilder query = new StringBuilder("select * from xy where id=@id");
if(useName) 
 query.Append(" AND name=@name");

SqlCommand cmd = new SqlCommand(query.ToString());
// add ID param
if(useName) {
  // add name param
}

You could change your query to您可以将查询更改为

"SELECT * FROM xy WHERE id = @id and (@name = '' OR name = @name");

Saves messing about with your query when the parameter has no value.当参数没有值时,可以避免弄乱您的查询。

SqlCommand cmd = new SqlCommand();
if(txtUsername.Text != string.Empty)
{
cmd.CommandText = "select * from xy where id = @id and name = @name";
cmd.Parameters.Add["@name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = txtUsername.Text;
}
else
{
cmd.CommandText = "select * from xy where id = @id";
}

Have a look at stringtemplate.org.看看 stringtemplate.org。 ST allows for all kinds of text construction and is very flexible. ST 允许各种文本构造,并且非常灵活。

If your example is the only query that needs runtime construction then ST is overkill.如果您的示例是唯一需要运行时构造的查询,那么 ST 是多余的。 But I am currently working on a project with many queries and ST made me happy.但我目前正在从事一个有很多疑问的项目,ST 让我很高兴。 The fact that all your queries are stored in a single file and not spread out inside many C# classes is enough to make the transition to ST worthwhile.您的所有查询都存储在一个文件中,而不是分散在许多 C# 类中,这一事实足以使过渡到 ST 是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM