Click here to Skip to main content
12,996,852 members (116,383 online)
Click here to Skip to main content
Add your own
alternative version

Stats

28.4K views
414 downloads
42 bookmarked
Posted 31 Jan 2010

Building Insert and Update Statements Automatically

, 31 Jan 2010
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

You may also be interested in...

Comments and Discussions

 
Questioncan u give a example which use this class to insert a table or update a table ? Pin
milad201022-Jul-10 10:04
membermilad201022-Jul-10 10:04 
GeneralMy vote of 2 Pin
Lalit K Chaudhary30-Jun-10 6:03
memberLalit K Chaudhary30-Jun-10 6:03 
GeneralAnother way Pin
Dwight Johnson12-Feb-10 4:04
memberDwight Johnson12-Feb-10 4:04 
QuestionNo Example? Pin
mbielski9-Feb-10 4:14
membermbielski9-Feb-10 4:14 
QuestionNot safe? Pin
Joe Enos1-Feb-10 7:57
memberJoe Enos1-Feb-10 7:57 
GeneralOther things to consider Pin
icestatue1-Feb-10 2:10
membericestatue1-Feb-10 2:10 
GeneralNice, but... Pin
jw12331-Jan-10 23:05
memberjw12331-Jan-10 23:05 
GeneralRe: Nice, but... Pin
Arno Petersen1-Feb-10 4:14
memberArno Petersen1-Feb-10 4:14 
GeneralRe: Nice, but... Pin
Ed Bouras9-Feb-10 3:21
memberEd Bouras9-Feb-10 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web01 | 2.8.170622.1 | Last Updated 1 Feb 2010
Article Copyright 2010 by Arno Petersen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid