DEV Community

DIVAKAR UPADHYAY
DIVAKAR UPADHYAY

Posted on Originally published at devladder.pages.dev

Parameters and SQL injection (ADO.NET)

👉 Full lesson with practice questions on DevLadder (free, lesson 3 of 9 in the ADO.NET: Connected & Disconnected Data Access course)

// ❌ NEVER: SQL injection: name = "x'; DROP TABLE Users;--"
var bad = new SqlCommand("SELECT * FROM Users WHERE Name = '" + name + "'", conn);

// ✅ Parameterised
var good = new SqlCommand("SELECT * FROM Users WHERE Name = @name", conn);
good.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = name;
Enter fullscreen mode Exit fullscreen mode
  • Parameters send values separately from SQL text: they are never executed as code.
  • Prefer Parameters.Add(name, SqlDbType, size) over AddWithValue: AddWithValue infers the type (e.g. nvarchar(4000) for strings), which can cause implicit conversions that prevent index seeks (varchar column vs nvarchar parameter) and plan-cache bloat.
  • Pass DBNull.Value for nulls, not null.
  • Dynamic table/column names can't be parameters: validate against an allow-list or use QUOTENAME in SQL.

Interview questions on ADO.NET

What is ADO.NET? Name its main objects.

ADO.NET is .NET's core data access library (System.Data + provider packages). Main objects: Connection (connects to the DB), Command (executes SQL/procs), Parameter, DataReader (forward-only fast read), DataAdapter (fills/updates DataSets), DataSet/DataTable (in-memory data), Transaction. For SQL Server use Microsoft.Data.SqlClient (SqlConnection, SqlCommand...).

What is the difference between connected and disconnected architecture?

Connected: the connection stays open while you read with a DataReader: forward-only, read-only, very fast, minimal memory. Disconnected: a DataAdapter fills a DataSet/DataTable, then closes the connection; you can navigate, edit and later push changes back with Update(): more memory, more flexibility. Modern apps mostly use the connected model (directly or via Dapper/EF).

What is the difference between ExecuteReader, ExecuteScalar and ExecuteNonQuery?

ExecuteReader returns a DataReader for one or more result sets. ExecuteScalar returns the first column of the first row (COUNT, SUM, new identity via OUTPUT/SCOPE_IDENTITY()). ExecuteNonQuery runs INSERT/UPDATE/DELETE/DDL and returns the number of rows affected (-1 for statements that don't affect rows, or when SET NOCOUNT ON is set).


Read the full lesson with progress tracking and the rest of the course on DevLadder: free step-by-step tutorials and interview questions for developers.

Next in the course: Stored procedures and output parameters →

Top comments (0)