Search code examples
c#sqlparameterized-query

Parameterized SQL in C# Application


I'm building a SQL query, trying to make it safer by using a parameterized query. I've got the below, does this look ok or is there anything I can/need to change?

// Connection to SQL
string connectionString = "Data Source= PC\\SQL;Initial Catalog= Catalog;Integrated Security=False; User ID=; Password=";

// SQL Insert Command - Must Use The Below For Commands!
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand Insert = new SqlCommand("INSERT INTO database (OS) VALUES (@ad)", connection);
Insert.Parameters.AddWithValue("@ad", adtb.text);

connection.Open();
Insert.ExecuteNonQuery();
connection.Close();

I've left out certain details (db name etc).

Any help or suggestions will be greatly appreciated!


Solution

  • You should do it like this:-

    // Read this connection string from `Web.Config` file instead.
    string connectionString = "Data Source= PC\\SQL;
       Initial Catalog= Catalog;Integrated Security=False; User ID=; Password=";
    

    Can be written as follows to avoid re-compiling every time you change the connection strings:-

    string connectionString  = ConfigurationManager.ConnectionString["YourKey"]
                                                      .ConnectionString;
    

    Consider using using statement to dispose your valuable resources:

    using(SqlConnection connection = new SqlConnection(connectionString))
    using(SqlCommand Insert = new SqlCommand("INSERT INTO database (OS) 
                                                  VALUES (@ad)", connection))
    {
        Insert.Parameters.Add("@ad", SqlDbType.NVarchar,10).Value = adtb.text;
        connection.Open();
        Insert.ExecuteNonQuery();
    }
    

    Avoid using AddWithValue, Read this.