How to insert a variable instead of 74 into this query?

SqlCommand SelectDannieComand = new SqlCommand("SELECT * FROM [ParserDB] WHERE Id > 74", sqlConnection); 

2 answers 2

In a competent way, this is done through parameterized queries:

 private void SomeThing(string id) { string sqlExpression = "SELECT Abc, Def FROM [ParserDB] WHERE Id > @id"; using (SqlConnection connection = new SqlConnection(ConString)) { using (SqlCommand command = new SqlCommand(sqlExpression, connection)) { connection.Open(); SqlParameter nameParam = new SqlParameter("@id", id); command.Parameters.Add(nameParam); SqlDataReader reader = command.ExecuteReader(); // ... } } } 

There is a simpler option (through the formatting of the string), it is simpler, but insecure (there is a possibility of SQL injection), therefore it is not recommended to use.

Also, the option with placeholders allows the SQL server to cache query execution plans, see for example here .

  • AK, as always, thanks! I just understood the parameters, collected the same, but could not verify, now I understand that I collected everything correctly. - Vipz

You should pass data through the SqlCommand.Parameters parameters. Or refuse to work with SqlCommand / SqlDataReader

As an alternative to SqlCommand it is worth looking at any lightweight ORM, for example, Dapper :

Package Manager Console:

 Install-Package Dapper 

 using Dapper; public class Dannie { public int Id { get; set; } public int SomeColumn { get; set; } } ... private void GetDannie(int id) { using (var connection = new SqlConnection(connectionString)) { connection.Open(); var d = connection.Query<Dannie>( "SELECT * FROM [ParserDB] WHERE Id > @id", new { id }) .ToList(); ... } } 
  • Plus for Dapper. Lightweight, modern, comfortable. - AK