string alpha="this is text";
string sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ('alpha')";
Which is the right syntax to pass a c# variable into an sql command?
string alpha="this is text";
string sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ('alpha')";
Which is the right syntax to pass a c# variable into an sql command?
Here's just one very simple method:
var yourTextValue = "this is text";
using (var db = new SqlConnection()) {
db.Open();
var command =
new SqlCommand("INSERT INTO dokimastikospinakas (pliroforia) VALUES (@textValue);", db);
command.Parameters.AddWithValue("@textValue", yourTextValue);
command.ExecuteNonQuery();
}
EDIT: You'd actually need some connection string for SqlConnection constructor, of course. And modified variable names by popular demand.
@id variable name is a bit weak, but the answer is correct.@phlargosmarfin instead.To avoid sql injection vulnerabilities, I recommend:
string alpha="this is text";
SqlCommand sqlComm = new SqlCommand();
sqlComm.CommandText = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@var)";
sqlComm.AddWithValue("@var", alpha);
..etc.
string insert = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@alpha)";
using (SqlConnection connection = new SqlConnection(...))
{
connection.Open();
using (SqlCommand command = new SqlCommand(insert, connection))
{
command.Parameters.Add("@alpha", alpha);
command.ExecuteNonQuery();
}
}
Are you using ADO.NET? Then parameterized queries are what you want:
IDbCommand command = new IDbCommand();
// Set up command connection
command.Text = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@alpha)";
command.Parameters.Add(new SqlParameter("@alpha", alpha));
The above code snippet of course depends on the type of database you are using (especially which type of SqlParameter you add.
Example using a OracleCommand object: OraCon is the OracleConnection.
string sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ( :Alpha )";
OracleCommand cmd = new OracleCommand(sql, OraCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(":Alpha", alpha);
cmd.ExecuteNonQuery();