Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / SQL
Article

C# class that creates 'INSERT INTO' SQL queries

Rate me:
Please Sign up or sign in to vote.
2.49/5 (23 votes)
16 Dec 2004 173K   32   18
Class that creates INSERT INTO SQL queries.

Introduction

This article describes a C# class that creates INSERT INTO SQL queries.

Some days ago, I was forced to work on an old application written in FoxPro for DOS. That meant struggling with DBF files. I used OleDB for FoxPro. It worked all okay, but I had trouble when I needed to insert rows into a table that had 50 (or more) columns. I had to specify all columns in the INSERT query. Horrible.

So I've written a small class that creates the query for me. It is short and here is the code:

C#
public class Insert
{
    Hashtable args = new Hashtable();
    string table;

    /// <summary>
    /// Constructs Insert object
    /// </summary>
    /// <param name="table">table name to insert to</param>
    public Insert(string table)
    {
        this.table = table;
    }

    /// <summary>
    /// Adds item to Insert object
    /// </summary>
    /// <param name="name">item name</param>
    /// <param name="val">item value</param>
    public void Add(string name, object val)
    {
        args.Add(name, val);
    }

    /// <summary>
    /// Removes item from Insert object
    /// </summary>
    /// <param name="name">item name</param>
    public void Remove(string name)
    {
        try
        {
            args.Remove(name);
        }
        catch
        {
            throw (new Exception("No such item"));
        }
    }

    /// <summary>
    /// Test representatnion of the Insert object (SQL query)
    /// </summary>
    /// <returns>System.String</returns>
    public override string ToString()
    {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();

        IDictionaryEnumerator enumInterface = args.GetEnumerator();
        bool first = true;
        while(enumInterface.MoveNext())
        {
            if (first) first = false;
            else
            {
                s1.Append(", ");
                s2.Append(", ");
            }
            s1.Append(enumInterface.Key.ToString());
            s2.Append(enumInterface.Value.ToString());
        }

        return "INSERT INTO " + table + " (" + s1 + ") VALUES (" + s2 + ");";
    }

    /// <summary>
    /// Gets or sets item into Insert object
    /// </summary>
    object this[string key]
    {
        get
        {
            Debug.Assert(args.Contains(key), "Key not found");
            return args[key];
        }
        set {args[key]=value;}
    }
}

You can use it this way:

C#
Insert q = new Insert("table_name");

q.Add("column1", "value1");
q.Add("column2", "value2");

string query = q.ToString();

Handy, if you have 50+ columns, each one calculated some way. Sorry for my bad English ;)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
4d.kh4n20-Dec-22 7:55
professional4d.kh4n20-Dec-22 7:55 
QuestionSystem.NullReferenceException ? Pin
Bastar Media12-Jun-16 22:32
Bastar Media12-Jun-16 22:32 
GeneralInsert File into Microsoft Office Access database field """"""""""""" Pin
Babita Shivade26-Mar-09 3:29
Babita Shivade26-Mar-09 3:29 
GeneralNo! You are setting people up for SQL Injection attacks Pin
SeattleVegas31-Oct-07 23:29
SeattleVegas31-Oct-07 23:29 
If someone goes and uses this class to add end user collected input to their DB you've just exposed them to a SQL Injection attack.

http://en.wikipedia.org/wiki/SQL_injection[^]

You should always use parameterized queries and not build up SQL statements.
GeneralRe: No! You are setting people up for SQL Injection attacks Pin
Waseem Sindhu21-Nov-08 20:24
Waseem Sindhu21-Nov-08 20:24 
Generalfree tables (dbf) Pin
Amar Chaudhary18-Oct-06 20:01
Amar Chaudhary18-Oct-06 20:01 
QuestionWhat about using OleDBCommandBuilder ? Pin
max295012-Dec-05 7:48
max295012-Dec-05 7:48 
GeneralInput checking Pin
mark_e_mark16-Sep-05 6:16
mark_e_mark16-Sep-05 6:16 
GeneralRe: Input checking Pin
Adam Klobukowski16-Sep-05 7:17
Adam Klobukowski16-Sep-05 7:17 
GeneralRe: Input checking Pin
mark_e_mark16-Sep-05 7:23
mark_e_mark16-Sep-05 7:23 
GeneralThanks Pin
Adam Klobukowski19-Dec-04 22:15
Adam Klobukowski19-Dec-04 22:15 
GeneralRe: Thanks Pin
Member 1372826021-Mar-18 3:37
Member 1372826021-Mar-18 3:37 
QuestionWhy do this manually? Pin
Matthew Noonan17-Dec-04 8:58
Matthew Noonan17-Dec-04 8:58 
AnswerRe: Why do this manually? Pin
Matthew Noonan17-Dec-04 9:00
Matthew Noonan17-Dec-04 9:00 
GeneralRe: Why do this manually? Pin
_jobo_10-Nov-05 16:44
_jobo_10-Nov-05 16:44 
GeneralRe: Why do this manually? Pin
Matthew Noonan13-Nov-05 13:41
Matthew Noonan13-Nov-05 13:41 
GeneralA couple more suggestions Pin
Marc Clifton16-Dec-04 5:52
mvaMarc Clifton16-Dec-04 5:52 
Generalsome improvements... Pin
MrRotzi16-Dec-04 5:37
MrRotzi16-Dec-04 5:37 

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.