String.Format 和 SqlParameters [英] String.Format and SqlParameters

查看:46
本文介绍了String.Format 和 SqlParameters的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览有关 .Net 中字符串格式的文档,但还没有找到这一点,希望有人能指出我正确的方向.我遇到了一段工作代码,它采用 SqlParameters 并将它们放入这样的字符串中:

I've been looking through the documentation on string formatting in .Net and haven't found this bit yet, and was hoping someone could point me in the right direction. I've come across a working piece of code that takes SqlParameters and puts them in a string like this:

        SqlParameter[] arrParams = new SqlParameter[]
        {
            new SqlParameter("@ClientID", clid),
            new SqlParameter("@CustomerID", cuid),
            new SqlParameter("@AdminUser", false)
        };
        string sqlText = string.Format("Insert into [Table1] (RID, CustomerID, AdminUser) values (@ClientID,@CustomerID,@AdminUser)");

..并且当在 SqlCommand 中沿行运行该字符串时,正确的值被放入正确的位置.我习惯于使用花括号作为字符串格式参数而不是 @ 符号,所以想知道在哪里可以了解更多信息?

..and when running that string down the line in a SqlCommand the proper values are put into the right spots. I'm used to using curly braces for string formatting arguments and not the @symbol and so was wondering where to learn more about this?

推荐答案

这段代码实际上不需要 String.Format.

This code does not actually need String.Format.

String.Format 适用于您通常会执行字符串"+ 变量 +更多字符串"的情况.这将被写成 String.Format("string{0}morestring", variable); 在这种情况下,它只是一个字符串,所以这就是为什么没有必要......什么都不是连接在一起.

String.Format is for times when you would normally do "string" + variable + "more string". This would be written as String.Format("string{0}morestring", variable); In this case, it is just one string, so that is why there is no need...nothing is being concatenated together.

这里有很好的 String.Format 解释

这里发生的事情是 @VariableName 正在填充您的 SqlParameters 以避免 SQL 注入.简而言之,当您创建 SqlParameter 时,.NET 库会查找与名称匹配的 SQL 参数,它可以是存储过程、函数等,也可以是 SQL 文本中的任何项目以@ 开头并匹配名称.

What is happening here is that the @VariableName is being filled with your SqlParameters to avoid SQL Injection. In a nutshell, when you create a SqlParameter, the .NET library looks for either a SQL parameter that matches the name, which could be a stored procedure, function, etc, or any item in a SQL text that begins with @ and matches the name.

这里很好地解释了 SqlParameters 的工作原理

这篇关于String.Format 和 SqlParameters的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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