Click here to Skip to main content
Licence CPOL
First Posted 31 Jan 2010
Views 18,318
Downloads 213
Bookmarked 43 times

Building Insert and Update Statements Automatically

By | 31 Jan 2010 | Article
Classes to build insert and update statements for Microsoft SQL, OleDb and ODBC dataprovider
 
Part of The SQL Zone sponsored by
See Also

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)

About the Author

Arno Petersen

Software Developer
B+S Card Service
Germany Germany

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questioncan u give a example which use this class to insert a table or update a table ? Pinmembermilad201010:04 22 Jul '10  
GeneralMy vote of 2 PinmemberLalit K Chaudhary6:03 30 Jun '10  
GeneralAnother way PinmemberDwight Johnson4:04 12 Feb '10  
QuestionNo Example? Pinmembermbielski4:14 9 Feb '10  
QuestionNot safe? PinmemberJoe Enos7:57 1 Feb '10  
GeneralOther things to consider Pinmembericestatue2:10 1 Feb '10  
GeneralNice, but... Pinmemberjw12323:05 31 Jan '10  
GeneralRe: Nice, but... PinmemberArno Petersen4:14 1 Feb '10  
GeneralRe: Nice, but... PinmemberEd Bouras3:21 9 Feb '10  

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.

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