如何从这段代码中删除Formatexception? [英] How Do I Remove The Formatexception From This Fragment Of Code?
问题描述
string cmdText = String.Format(select physical_name FROM sys.master_files where name = {0}+ userSideDatabaseName);
这段代码应返回我是一个路径,但它给出了以下错误:
索引(从零开始)必须大于或等于零且小于参数列表的大小。
任何建议?
string cmdText=String.Format( "Select physical_name FROM sys.master_files where name={0}"+userSideDatabaseName);
This piece of code should return me a path but it is giving the following error:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Any Suggestions?
推荐答案
只需用','代替'+':
Just replace the '+' with a ',':
string cmdText = String.Format("Select physical_name FROM sys.master_files where name='{0}'", userSideDatabaseName);
但是:基于变量/未知输入构造SQL查询是一种非常糟糕的做法。
更好,更清洁,更安全的方式是使用参数化查询:
BUT: this is a very bad practice to construct SQL queries based on variable/unknown inputs.
A better, cleaner, more secure way would be to use a parameterized query:
string cmdText = "Select physical_name FROM sys.master_files where name=@name";
SqlCommand cmd = new SqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@name", userSideDatabaseName);
它可以防止任何SQL注入攻击。
It would prevent any SQL injection attack.
这篇关于如何从这段代码中删除Formatexception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!