How to dynamically build an insert command from Datatable in c#

后端 未结 2 1531
夕颜
夕颜 2020-12-31 19:08

I am facing some problem with making a SQL insert statement dynamically from a dataTable object in c#. I want to know the best practices to make it.Here is my code snippet ,

相关标签:
2条回答
  • 2020-12-31 20:05
       ## Dynamic Update Query from Datatable with Npgsql##
      public string UpdateExecute(DataTable dataTable, string TableName)
    {
    
        NpgsqlCommand cmd = null;
        string Result = String.Empty;
    
        try
        {            
    
            if (dataTable.Columns.Contains("skinData")) dataTable.Columns.Remove("skinData");
            string columns = string.Join(",", dataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName));
    
            string values = string.Join(",", dataTable.Columns.Cast<DataColumn>().Select(c => string.Format("@{0}", c.ColumnName)));
    
            StringBuilder sqlCommandInsert = new StringBuilder();
            sqlCommandInsert.Append("Update " + TableName + " Set ");
    
            string[] TabCol = columns.Split(',');
            string[] TabVal = values.Split(',');
    
            for (int i = 0; i < TabCol.Length; i++)
            {
                for (int j = 0; j < TabVal.Length; j++)
                {
                    sqlCommandInsert.Append(TabCol[i] +" = "+ TabVal[i] + ",");
                    break;
                }
            }
          string  NpgsqlCommandUpdate= sqlCommandInsert.ToString().TrimEnd(',');
          NpgsqlCommandUpdate += (" where " + TabCol[0] + "=" + TabVal[0]);
    
    
            using (var con = new NpgsqlConnection("Server=localhost;Port=5432;uid=uapp;pwd=Password;database=Test;"))
            {
                con.Open();
                foreach (DataRow row in dataTable.Rows)
                {
                    cmd = new NpgsqlCommand(NpgsqlCommandUpdate.ToString(), con);
                    cmd.Parameters.Clear();
                    foreach (DataColumn col in dataTable.Columns)
                        cmd.Parameters.AddWithValue("@" + col.ColumnName, row[col]);
    
                    Result = cmd.ExecuteNonQuery().ToString();
                }
            }
        }
        catch (Exception)
        {
            Result = "-1";
        }
        return Result;
    }   
    
    0 讨论(0)
  • 2020-12-31 20:14

    Use VALUES instead of VALUE. Apart from that you should always use sql-parameters:

    string columns = string.Join("," 
        , dataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName));
    string values = string.Join("," 
        , dataTable.Columns.Cast<DataColumn>().Select(c => string.Format("@{0}", c.ColumnName)));
    String sqlCommandInsert = string.Format("INSERT INTO dbo.RAW_DATA({0}) VALUES ({1})" , columns, values);
    
    using(var con = new SqlConnection("ConnectionString"))
    using (var cmd = new SqlCommand(sqlCommandInsert, con))
    {
        con.Open();
        foreach (DataRow row in dataTable.Rows)
        {
            cmd.Parameters.Clear();
            foreach (DataColumn col in dataTable.Columns)
                cmd.Parameters.AddWithValue("@" + col.ColumnName, row[col]);
            int inserted = cmd.ExecuteNonQuery();
        }
    }
    
    0 讨论(0)
提交回复
热议问题