Reputation: 81
For example, when creating a command text for a SqlServer ce statement, the example has you use
command.CommandText = "INSERT INTO Region (RegionID, RegionDescription) VALUES (@id, @desc)";
I understand how to run sql queries, but have always just passed the database system a string with sql statements. This is new to me, and I would like to understand. Does the @ mean that it is a variable, so when it parses the string, it will insert the value of the variable id into the string where it says @id?
I know in php, double quotes allow the parser to parse a variable value within a string, and am wondering if this is similar.
However, to test it, I made a simple program to test this theory.
string id = "FOO";
MessageBox.Show("@id");
It showed the literal @id, so this has left me confused. Thanks ahead for any help! I just feel the need to understand what I am typing, not just mindlessly following the examples.
Upvotes: 0
Views: 344
Reputation: 85468
@
has a special meaning in the SQL (T-SQL) query (ie: it is used to parametrize the query), but in a C# string you just get the literal @
. Actually, command.CommandText
is still a string with the @
characters; the substitution takes place only when needed (ie: query is executed).
If you want interpolation in C#, use String.Format()
, eg:
string name = "John";
string greet = String.Format("Hello, {0}", name);
// this also works
Console.WriteLine("Hello, {0}", name);
Upvotes: 3
Reputation: 269418
The @
symbol, in this case, is used to parameterize a SQL command, not for general-purpose variable substitution within a string
.
command.CommandText = "INSERT INTO Region (RegionID, RegionDescription) " +
"VALUES (@id, @desc)";
command.Parameters.AddWithValue("@id", 42);
command.Parameters.AddWithValue("@desc, "Description of region forty-two.");
Upvotes: 3
Reputation: 7781
In this case @
defines the variable that you want to pass into your SQL statement.
For instance:
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = 666;
And then you add it to your command like that:
command.Parameters.Add(param);
Then, in your select
@id
and @desc
will use values passed as a value of SqlParameter.
Therefore, if you just output "@id"
it will be interpreted as a normal string. It only makes sense while used inside a SQL query.
Upvotes: 3