65.9K
CodeProject is changing. Read more.
Home

Building Insert and Update Statements Automatically

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.45/5 (5 votes)

Feb 1, 2010

CPOL

2 min read

viewsIcon

41181

downloadIcon

461

Classes to build insert and update statements for Microsoft SQL, OleDb and ODBC dataprovider

Introduction

While working with databases, you have to create insert and update statements many times. But this is boring work. Furthermore, the code could be more clear if it's not interrupted by SQL statements. With an OR-mapper like NHibernate, you can get rid of this problem. But sometimes, you can't use an OR-Mapper or you don't want to use it. This is the reason I wrote this little SqlStatementBuilder. I decided to use Parameters in the DbCommand to prevent SQL injection. As every dataprovider handles the parameters differently, I had to write a Statementbuilder for each dataprovider. Since I haven't installed an Oracle database, I still have not added a StatementBuilder for Oracle. The basic work is done in the base class StatementBuilderBase. Only the parameter handling and the database datatypes are covered by the child classes.

How the Code Works

The StatementBuilder has got two methods; one for inserts, one for updates. These methods are called with a list of fields and values and the name of the table that should be changed. In addition, the StatementBuilder needs the DBCommand that will execute the statement. The StatementBuilder sets the CommandText property of the given DbCommand and fills the parameterlist of the command. Here is the method for the insert:

public IDbCommand CompleteInsertCommand
	(IDbCommand command, string tablename,  List<keyvaluepair><string> columnList)
{
    StringBuilder sb = new StringBuilder();
    GetInsertTextForFields(tablename, columnList, sb);
    GetInsertTextForValues(columnList, sb);

    command.CommandText = sb.ToString();

    AddParameters(columnList, command);

    return command;
}

At first, the method GetInsertTextForFields is called to build the first part of the insert statement such as INSERT INTO table (field1, field2, field3, fieldn):

private static void GetInsertTextForFields
	(string tablename, List<keyvaluepair><string> columnList, StringBuilder sb)
{
    sb.Append("INSERT INTO ");
    sb.Append(tablename);
    sb.Append(" (");

    KeyValuePair<string> lastCol = columnList.Last();

    foreach (KeyValuePair<string> col in columnList)
    {
        sb.Append(col.Key);
        if (columnList.Last().Key != col.Key)
        {
            sb.Append(", ");
        }
    }
    sb.AppendLine(")");
}

Thereafter the values of the statement follow (such as VALUES (@field1,@field2,@field3,@fieldn) respectively VALUES (?,?,?,?):

private void GetInsertTextForValues (List> ColumnList, StringBuilder sb)
(
    sb.Append ( "VALUES (");
    SetInsertParameter(columnList, sb);
    sb.Append (")");
)

SetInsertParameters is implemented in the child classes. For example, the SqlStatementBuilder for Microsoft SQL implements this function like this:

foreach (KeyValuePair<string> col in columnList)
{
    sb.Append(parameterChar);
    sb.Append(col.Key);
    if (columnList.Last().Key != col.Key)
    {
        {
        sb.Append(", ");
        }
    }
}

Last, the parameters are added. For Microsoft SQL, it looks like this:

protected override void AddParameters
	(List<keyvaluepair><string> columnList, IDbCommand command)
{
    if (!(command is SqlCommand))
    {
        throw new System.ArgumentException();
    }
    SqlCommand sqlCommand = (SqlCommand)command;

    foreach (KeyValuePair<string> col in columnList)
    {
           sqlCommand.Parameters.Add(col.Key, GetDataType(col.Value)).Value = col.Value;
    }
}

To add the parameters, we have to know the database datatypes of the parameter. This work is done by the method getDataType in the child classes. The database datatype is determined by using the datatype of the given value. This has the advantage that the user does not need the permission to read the schema of the database. To avoid updates on all rows of the table by forgetting the where clause, the method CompleteUpdateCommand must additionally be called with the where clause.

History

  • 1st February, 2010: Initial post