Click here to Skip to main content
15,885,204 members
Articles / Programming Languages / C#
Article

Building Insert and Update Statements Automatically

Rate me:
Please Sign up or sign in to vote.
3.45/5 (5 votes)
31 Jan 2010CPOL2 min read 40.4K   459   42   8
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:

C#
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):

C#
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 (?,?,?,?):

C#
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:

C#
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:

C#
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)


Written By
Software Developer B+S Card Service
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

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
milad201022-Jul-10 10:04 
GeneralMy vote of 2 Pin
Lalit K Chaudhary30-Jun-10 6:03
Lalit K Chaudhary30-Jun-10 6:03 
GeneralAnother way Pin
Dwight Johnson12-Feb-10 4:04
Dwight Johnson12-Feb-10 4:04 
QuestionNo Example? Pin
mbielski9-Feb-10 4:14
mbielski9-Feb-10 4:14 
QuestionMessage Removed Pin
1-Feb-10 7:57
User 30424981-Feb-10 7:57 
GeneralOther things to consider Pin
icestatue1-Feb-10 2:10
icestatue1-Feb-10 2:10 
GeneralNice, but... Pin
jw12331-Jan-10 23:05
jw12331-Jan-10 23:05 
GeneralRe: Nice, but... Pin
Arno Petersen1-Feb-10 4:14
Arno Petersen1-Feb-10 4:14 
GeneralRe: Nice, but... Pin
Middle Manager9-Feb-10 3:21
Middle Manager9-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.