Insert command string building

I could not find the error in the following insert command string. Let me know if you notice any. What is the best way to build this type of command string.It becomes very difficult to find error if whole string showing red ~. I have picked every data value with pm. manually to avoid any chance or error.

cmd = new OleDbCommand("insert into ProjectMaster (ProjectCode, TransactionType, Description, Justification, RequesterName, RquesterID) values ('" +
    pm.ProjectCode + "','" + pm.TransactionType + "','" +
    pm.Description + "','" + pm.Justification + "','" +
    pm.RequesterName + "','" + pm.RequesterID  + "')", con);

    cmd.ExecuteNonQuery();
Jon Skeet
people
quotationmark

What is the best way to build this type of command string.

You use parameterized SQL. Do not concatenate the values you want to use into the SQL like this. It opens you up to SQL injection attacks, conversion errors, and generally messy code.

You use code such as:

// Obviously fill in the "..." with the rest of the fields you need to use
string sql = "INSERT INTO ProjectMaster (ProjectCode, TransactionType, ...) "
           + "VALUES (@ProjectCode, @TransactionType, ...)";
using (var connection = new SqlConnection(...))
{
    connection.Open();
    using (var command = new SqlCommand(sql, connection))
    {
        // Check the parameter types! We don't know what they're meant to be
        command.Parameters.Add("@ProjectCode", SqlType.NVarChar).Value = ...;
        command.Parameters.Add("@TransactionType", SqlType.NVarChar).Value = ...;
        ...
        command.ExecuteNonQuery();
    }
}

Also, consider using an ORM instead of raw SQL.

people

See more on this question at Stackoverflow