Best Practices - Executing SQL Statements
suggest changepublic void SaveNewEmployee(Employee newEmployee)
{
// best practice - wrap all database connections in a using block so they are always closed & disposed even in the event of an Exception
// best practice - retrieve the connection string by name from the app.config or web.config (depending on the application type) (note, this requires an assembly reference to System.Configuration)
using(SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionName"].ConnectionString))
{
// best practice - use column names in your INSERT statement so you are not dependent on the sql schema column order
// best practice - always use parameters to avoid sql injection attacks and errors if malformed text is used like including a single quote which is the sql equivalent of escaping or starting a string (varchar/nvarchar)
// best practice - give your parameters meaningful names just like you do variables in your code
using(SqlCommand sc = new SqlCommand("INSERT INTO employee (FirstName, LastName, DateOfBirth /*etc*/) VALUES (@firstName, @lastName, @dateOfBirth /*etc*/)", con))
{
// best practice - always specify the database data type of the column you are using
// best practice - check for valid values in your code and/or use a database constraint; if inserting NULL then use DBNull.Value
sc.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar, 200){Value = newEmployee.FirstName ?? (object) System.DBNull.Value});
sc.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar, 200){Value = newEmployee.LastName ?? (object) System.DBNull.Value});
// best practice - always use the correct types when specifying your parameters, Value is assigned to a DateTime instance and not a string representation of a Date
sc.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date){ Value = newEmployee.DateOfBirth });
// best practice - open your connection as late as possible unless you need to verify that the database connection is valid and won't fail and the preceding code takes a long time (not the case here)
con.Open();
sc.ExecuteNonQuery();
}
// the end of the using block will close and dispose the SqlConnection
// best practice - end the using block as soon as possible to release the database connection
}
}
// supporting class used as parameter for example
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Best practice for working with ADO.NET
- Open the connection for as little time as possible. Close it explicitly once the command has finished so the connection returns to the pool. The default pool maximum size is 100. Connection pooling improves the performance of physical connections to SQL Server. See Connection Pooling in SQL Server.
- Wrap every database connection in a
usingblock so it is closed and disposed even if an exception is thrown. See using Statement (C# Reference). - Retrieve connection strings by name from
app.configorweb.config(depending on the application type). This requires an assembly reference toSystem.Configuration. See Connection Strings and Configuration Files. - Always pass incoming values as parameters. That avoids SQL injection, avoids errors when text contains a single quote (the SQL string delimiter), and lets the provider reuse query plans (not supported by every provider).
- When working with parameters:
- A mismatch of SQL parameter type or size is a common cause of insert, update, or select failure.
- Give parameters meaningful names, just as you do for variables.
- Specify the database data type of the column so the wrong parameter type is not used.
- Validate incoming values before you pass them to the command (“garbage in, garbage out”), and do it as early in the stack as possible.
- Assign a real
DateTimeinstance, not a string representation of a date. - Specify the size of string parameters. SQL Server can reuse execution plans when parameters match in type and size. Use
-1forMAX. - Do not use AddWithValue. It is easy to omit the parameter type, or the precision and scale when they are required. See Can we stop using AddWithValue already?.
- When using database connections:
- Open the connection as late as possible and close it as soon as possible. This applies to any external resource.
- Never share a connection instance (for example, a singleton that holds one
SqlConnection). Create a new connection when you need one, and dispose it when you are done, because:- Most providers pool connections, so creating a new managed connection is cheap.
- A shared instance breaks as soon as the code runs on more than one thread.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents