Click here to Skip to main content
Click here to Skip to main content

Building Insert and Update Statements Automatically

, 31 Jan 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Arno Petersen
Software Developer B+S Card Service
Germany Germany
No Biography provided

Comments and Discussions

 
Questioncan u give a example which use this class to insert a table or update a table ? Pinmembermilad201022-Jul-10 10:04 
GeneralMy vote of 2 PinmemberLalit K Chaudhary30-Jun-10 6:03 
GeneralAnother way PinmemberDwight Johnson12-Feb-10 4:04 
QuestionNo Example? Pinmembermbielski9-Feb-10 4:14 
QuestionNot safe? PinmemberJoe Enos1-Feb-10 7:57 
GeneralOther things to consider Pinmembericestatue1-Feb-10 2:10 
GeneralNice, but... Pinmemberjw12331-Jan-10 23:05 
GeneralRe: Nice, but... PinmemberArno Petersen1-Feb-10 4:14 
GeneralRe: Nice, but... PinmemberEd Bouras9-Feb-10 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141030.1 | Last Updated 1 Feb 2010
Article Copyright 2010 by Arno Petersen
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid