Search code examples
c#sqlparameterized

How to make a parameterized query in a method that made for SQL insertions?


I really don't know how to explain it well in the title, but here's my problem.

Among many overloading methods i have made this method that's its only purpose is to insert given values into a give table :

public static int Insert(string cs, string table, string[] values)
{
    using (SqlConnection con = new SqlConnection(cs))
    {
        try
        {
            string strCommand = string.Format(
                "INSERT INTO {0} VALUES ({1})", 
                table, 
                values.Aggregate((a, b) => (a + ", " +b)));
            SqlCommand com = new SqlCommand(strCommand, con);
            con.Open();
            int result = com.ExecuteNonQuery();
            return result;

        }
        catch (SqlException ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            return 0;
        }
    }
}

Right now it's not using parameterized queries, isn't it?

I really want to implement this concept into it but i have no idea how.


Solution

  • You can use Dictionary containing column names and their respective values

       Dictionary<string, object> values = new Dictionary<string,object>();
       values.Add("userid", 1022);
            values.Add("username", "JFord");
            values.Add("IsActive", 0);
       string table = "users";
    

    usage:

    MyClass.Insert("connection", "users", values);
    

    Method

    public static int Insert(string cs, string table, Dictionary<string,object> values)
    {
            string strCommand = string.Format("INSERT INTO {0} VALUES ({1})",
                table, "@"+String.Join(", @", values.Keys));
    
     //strCommand becomes: "INSERT INTO users VALUES (@userid, @username, @IsActive)"
    
            SqlCommand com = new SqlCommand(strCommand, conn);
    
            foreach (string key in values.Keys)
            {
                com.Parameters.AddWithValue("@" + key, values[key]);
            }
    
    }