FrmExec: Extract DataTable_GenerateInserts method to Utiles.

This commit is contained in:
2017-01-27 12:27:04 +01:00
parent ad041035f9
commit b1b74fc450
3 changed files with 142 additions and 105 deletions

View File

@@ -1,10 +1,16 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
namespace ServerExplorer.Code
{
public static class Utiles
{
#region File Utils
public static void CrearDirectorio(this String path)
{
DirectoryInfo info;
@@ -18,10 +24,97 @@ namespace ServerExplorer.Code
}
CrearDirectorio(info);
}
public static void CrearDirectorio(this DirectoryInfo info)
{
if (info.Parent != null) CrearDirectorio(info.Parent);
if (!info.Exists) info.Create();
}
#endregion
#region DataTable Utils
public static List<string> DataTable_GenerateInserts(DataTable dataTable, string destTable)
{
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
var listCmds = new List<string>();
// Recorrer la tabla de datos
foreach (DataRow dr in dataTable.Rows)
{
var sbColumns = new StringBuilder();
var sbValues = new StringBuilder();
foreach (DataColumn dc in dataTable.Columns)
{
// El nombre de la columna
if (sbColumns.Length > 0) { sbColumns.Append(", "); }
sbColumns.AppendFormat("[{0}]", dc.ColumnName);
// El valor de la columna
if (sbValues.Length > 0) { sbValues.Append(", "); }
object valor = dr[dc];
if (valor == DBNull.Value || valor == null)
{
// NULOS
sbValues.Append("NULL");
}
else
{
string type = dc.DataType.Name.ToLower();
if (type == "string")
{
// Cadenas
sbValues.AppendFormat("'{0}'", ((string)valor).Replace("'", "''"));
}
else if (type == "int" || type == "int32" || type == "int64")
{
// int
sbValues.Append(((int)valor).ToString(nfi));
}
else if (type == "long" || type == "int64")
{
// long
sbValues.Append(((long)valor).ToString(nfi));
}
else if (type == "decimal")
{
// Decimales
sbValues.Append(((decimal)valor).ToString(nfi));
}
else if (type == "bit" || type == "bool" || type == "boolean")
{
// Booleanos
sbValues.Append(((bool)valor) ? "1" : "0");
}
else if (type == "byte[]")
{
// Arrays de bytes (imagenes, archivos etc)
sbValues.AppendFormat("0x{0}", BitConverter.ToString(((byte[])valor)).Replace("-", ""));
}
else if (type == "datetime")
{
// DateTIme
sbValues.AppendFormat("'{0}'", ((DateTime)valor).ToString("yyyy-MM-dd HH:mm:ss"));
}
else
{
// Otros
sbValues.AppendFormat("'{0}'", valor.ToString());
}
}
}
// Insertar fila a la datatable destino
listCmds.Add(String.Format("INSERT INTO {0} ({1}) VALUES ({2})",
destTable, sbColumns.ToString(), sbValues.ToString()));
}
return listCmds;
}
#endregion
}
}