text stringlengths 0 13.4k |
|---|
Sql parameters type and size mismatch is a common cause of insert/ updated/ select failure |
Give your Sql parameters meaningful names just like you do variables in your code |
Specify the database data type of the column you are using, this ensures the wrong parameter types is |
not used which could lead to unexpected results |
Validate your incoming parameters before you pass them into the command (as the saying goes, |
"garbage in, garbage out"). Validate incoming values as early as possible in the stack |
Use the correct types when assigning your parameter values, example: do not assign the string value |
of a DateTime, instead assign an actual DateTime instance to the value of the parameter |
Specify the size of string-type parameters. This is because SQL Server can re-use execution plans if the |
parameters match in type and size. Use -1 for MAX |
Do not use the method AddWithValue, the main reason is it is very easy to forget to specify the |
parameter type or the precision/scale when needed. For additional information 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 is a general guideline |
when working with any external resource |
Never share database connection instances (example: having a singleton host a shared instance of |
type SqlConnection). Have your code always create a new database connection instance when needed |
and then have the calling code dispose of it and "throw it away" when it is done. The reason for this is |
Most database providers have some sort of connection pooling so creating new managed |
connections is cheap |
It eliminates any future errors if the code starts working with multiple threads |
Section 25.2: Executing SQL statements as a command |
// Uses Windows authentication. Replace the Trusted_Connection parameter with |
GoalKicker.com – .NET Framework Notes for Professionals |
88 |
// User Id=...;Password=...; to use SQL Server authentication instead. You may |
// want to find the appropriate connection string for your server. |
string connectionString = |
@"Server=myServer\myInstance;Database=myDataBase;Trusted_Connection=True;" |
string sql = "INSERT INTO myTable (myDateTimeField, myIntField) " + |
"VALUES (@someDateTime, @someInt);"; |
// Most ADO.NET objects are disposable and, thus, require the using keyword. |
using (var connection = new SqlConnection(connectionString)) |
using (var command = new SqlCommand(sql, connection)) |
{ |
// Use parameters instead of string concatenation to add user-supplied |
// values to avoid SQL injection and formatting issues. Explicitly supply datatype. |
// System.Data.SqlDbType is an enumeration. See Note1 |
command.Parameters.Add("@someDateTime", SqlDbType.DateTime).Value = myDateTimeVariable; |
command.Parameters.Add("@someInt", SqlDbType.Int).Value = myInt32Variable; |
// Execute the SQL statement. Use ExecuteScalar and ExecuteReader instead |
// for query that return results (or see the more specific examples, once |
// those have been added). |
connection.Open(); |
command.ExecuteNonQuery(); |
} |
Note 1: Please see SqlDbType Enumeration for the MSFT SQL Server-specific variation. |
Note 2: Please see MySqlDbType Enumeration for the MySQL-specific variation. |
Section 25.3: Using common interfaces to abstract away |
vendor specific classes |
var providerName = "System.Data.SqlClient"; //Oracle.ManagedDataAccess.Client, IBM.Data.DB2 |
var connectionString = "{your-connection-string}"; |
//you will probably get the above two values in the ConnectionStringSettings object from .config file |
var factory = DbProviderFactories.GetFactory(providerName); |
using(var connection = factory.CreateConnection()) { //IDbConnection |
connection.ConnectionString = connectionString; |
connection.Open(); |
using(var command = connection.CreateCommand()) { //IDbCommand |
command.CommandText = "{query}"; |
using(var reader = command.ExecuteReader()) { //IDataReader |
while(reader.Read()) { |
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.