Reputation: 16309
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)");
..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?
Upvotes: 0
Views: 2190
Reputation: 67075
This code does not actually need String.Format
.
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.
Here is a good explanation of String.Format
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.
And here is a good explanation of how SqlParameters work
Upvotes: 1
Reputation: 11
This is not similar to String.Format what is actually happening is you are running the SQL Command, the command looks for variables called @ClientID,@CustomerID and @AdminUser, which are passed to SQL Server as parameters. You will have something like cmd.Parameters = arrparams a bit further down.
The actual String.Format part around the SQL text is redundant you are right, it will been to use the curly brace route like you suggested.
Hope this helps.
Upvotes: 0
Reputation: 7759
I think there is some confusion here. The @
symbol is used to identify the named SQL parameters within the INSERT INTO
statement and not for String.Format
.
Upvotes: 0