C sharp - Volcar un csv a una bd sql

 
Vista:

Volcar un csv a una bd sql

Publicado por Pablo (1 intervención) el 18/07/2007 10:25:18
Hola tengo un problema con una aplicación que desarrollo mi empresa y que ahora tengo que mantener yo.
La aplicación coge un csv de unos 120 000 registros y cuelga toda la maquina haciendo la importación para la cual puede tardar unos 20-25 minutos
Hay alguna manera de que esto sea mas rápido? o por lo menos que nos se bloquee la máquina

Paso el código que utilizo

private void ImportarArchivoContadores()
{

System.IO.TextReader oFS;
string sFileFullName; string cmpContatxt; string sSql;
string sLine; string[] arrLine;
int i; string strTmp;
int codCli; int codSv; int codImpor; int codCont;
DateTime cmpDate; int cmpConta; double cmpValue; int colCount;
int numImpContOk=0; int numImpContError=0;
int duplicado = 0;
bool flagContinuar;

string sepDec = (1.2).ToString().Substring(1,1);
DSLogs dsLogsVis = new DSLogs();
DSLogs dsLg = new DSLogs();
DSLogs.LogsRow rowLg; DSContadoresClientes.ContadoresClientesRow rowContaCli; DSContadores.ContadoresRow rowConta;
DateTime dtIniFile = DateTime.Now; DateTime dtIniBd; DateTime dtFi;
TimeSpan ts;

sFileFullName = txtFileFullName.Text;
oFS = new StreamReader(sFileFullName, System.Text.Encoding.GetEncoding(1252));

// Configurar culture para transformacion de fechas
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-ES", true);
if ( cmbFormatoFecha.SelectedIndex == 1 )
culture = new System.Globalization.CultureInfo("en-US", true);
cmpDate = DateTime.Now;
try
{
codCli = int.Parse(cbCliente.SelectedValue.ToString());
codSv = int.Parse(cbServidor.SelectedValue.ToString());
cmpConta=0;

codImpor =_dac.GetImportacionesByParametrosComprobacion(codCli.ToString(), codSv.ToString(),
tbImportacion.Text);
flagContinuar=true;
if (codImpor != 0)
{
MessageBox.Show("El nombre de la importación seleccionado ya existe. Por favor seleccione otro nombre.");
flagContinuar=false;
}
else
{
codImpor = _dac.InsertImportacion(cmpDate, codCli, codSv, nombreArchivo, tbImportacion.Text);
}

if (flagContinuar == true)
{

sLine = oFS.ReadLine();
sLine = oFS.ReadLine();
sLine = oFS.ReadLine();
while( sLine != null && duplicado==0)
{
// Recuperar la fecha de la linea
string lineaCsv=sLine.Replace(",\"", "·\"");
arrLine =lineaCsv.Split('·');

cmpDate = DateTime.Parse(netejarValor(arrLine[0]), culture);

// Bucle por las diferentes columnas
for( i = 1; i<cmbContas.Length; i++)
{
cmpContatxt=cmbContas[i].Text.ToString();
cmpContatxt = "%" + cmpContatxt;
cmpContatxt = cmpContatxt.Substring(cmpContatxt.LastIndexOf("%"));

sSql = "";
sSql = "KeyES like '" + cmpContatxt + "'";
DSContadores.ContadoresRow[] rowsCont;
rowsCont = (DSContadores.ContadoresRow[])dsCont.Contadores.Select(sSql);

if (rowsCont.Length > 0)
{
codCont=rowsCont[0].Codigo;
sSql = "";
sSql = "CodigoCliente = " + codCli.ToString() +
" AND CodigoServidor = " + codSv.ToString() +
" AND CodigoContador = " + codCont.ToString();
DSContadoresClientes.ContadoresClientesRow[] rowsContCli;
rowsContCli = (DSContadoresClientes.ContadoresClientesRow[])dsContCli.ContadoresClientes.Select(sSql);
if (rowsContCli.Length > 0)
{
cmpConta=rowsContCli[0].Codigo;
}
else
{
try{
cmpConta = _dac.InsertContadorCliente( codCli, codSv, codCont );
rowContaCli = dsContCli.ContadoresClientes.NewContadoresClientesRow();
rowContaCli.Codigo = cmpConta;
rowContaCli.CodigoCliente = codCli;
rowContaCli.CodigoServidor = codSv;
rowContaCli.CodigoContador = codCont;
dsContCli.ContadoresClientes.AddContadoresClientesRow(rowContaCli);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
else
{
sSql = "";
sSql = "KeyEN like '" + cmpContatxt + "'";
DSContadores.ContadoresRow[] rowsContEn;
rowsContEn = (DSContadores.ContadoresRow[])dsCont.Contadores.Select(sSql);
if (rowsContEn.Length > 0)
{
codCont=rowsContEn[0].Codigo;
sSql = "";
sSql = "CodigoCliente = " + codCli.ToString() +
" AND CodigoServidor = " + codSv.ToString() +
" AND CodigoContador = " + codCont.ToString();
DSContadoresClientes.ContadoresClientesRow[] rowsContCli;
rowsContCli = (DSContadoresClientes.ContadoresClientesRow[])dsContCli.ContadoresClientes.Select(sSql);
if (rowsContCli.Length > 0)
{
cmpConta=rowsContCli[0].Codigo;
}
else
{
cmpConta = _dac.InsertContadorCliente( codCli, codSv, codCont );
rowContaCli = dsContCli.ContadoresClientes.NewContadoresClientesRow();
rowContaCli.Codigo = cmpConta;
rowContaCli.CodigoCliente = codCli;
rowContaCli.CodigoServidor = codSv;
rowContaCli.CodigoContador = codCont;
dsContCli.ContadoresClientes.AddContadoresClientesRow(rowContaCli);
}
}
else
{
try{
codCont=_dac.InsertContador(cmbContas[i].Text.ToString(), cmbContas[i].Text.ToString(), 1, "");
rowConta = dsCont.Contadores.NewContadoresRow();
rowConta.Codigo = codCont;
rowConta.Contador = cmbContas[i].Text.ToString();
rowConta.KeyES = cmbContas[i].Text.ToString();
rowConta.Conversion = 1;
rowConta.Leyenda = "";
dsCont.Contadores.AddContadoresRow(rowConta);

cmpConta = _dac.InsertContadorCliente( codCli, codSv, codCont );
rowContaCli = dsContCli.ContadoresClientes.NewContadoresClientesRow();
rowContaCli.Codigo = cmpConta;
rowContaCli.CodigoCliente = codCli;
rowContaCli.CodigoServidor = codSv;
rowContaCli.CodigoContador = codCont;
dsContCli.ContadoresClientes.AddContadoresClientesRow(rowContaCli);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
// Mirar si se ha seleccionado una columna valida
if ( Trojan.Utils.TryIsInt32(txtContas[i].Text) )
{
colCount = int.Parse(txtContas[i].Text);
if ( colCount < arrLine.Length - 1 )
{

// Modificar el valor para convertirlo a un decimal correcto
strTmp = arrLine[colCount];
strTmp = netejarValor(strTmp);
strTmp = strTmp.Replace(".", sepDec);
strTmp = strTmp.Replace(",", sepDec);
strTmp = "0" + strTmp.TrimStart(new char[]{' '});

try
{
// Convertir el valor a double
cmpValue = double.Parse(strTmp);

// Insertar el valor a BD
//_dac.InsertLogs(cmpDate, codCli, codSv, cmpConta, cmpValue);

rowLg = dsLg.Logs.NewLogsRow();
rowLg.Fecha = cmpDate;
rowLg.CodigoCliente = codCli;
rowLg.CodigoServidor = codSv;
rowLg.CodigoContador = cmpConta;
rowLg.Valor = cmpValue;
rowLg.IDImportacion = codImpor;
dsLg.Logs.AddLogsRow(rowLg);

if( _dac == null ) _dac = new Dalc();

if(numImpContOk==0) dsLogsVis = _dac.GetLogsByParametrosComprobacion(codCli.ToString(), codSv.ToString(), cmpConta.ToString(), cmpDate.ToString("dd/MM/yyyy HH:mm:ss.fff"));
if(dsLogsVis.Logs.Rows.Count > 0) duplicado = 1;

numImpContOk += 1;
}
catch(Exception ex)
{
if (numImpContError==0) MessageBox.Show(ex.Message);
numImpContError += 1;
}

}
} //If IsNumeric(txtContas(i).Text)
}

//if ((numImpContOk % 5) == 0)
//{
StatusBar1.Text = "Importados " + numImpContOk.ToString();
if (numImpContError > 0) StatusBar1.Text += " (Errores " + numImpContError.ToString() + ")";
this.Refresh();
Application.DoEvents();
//}

// Recuperar la siguiente linea
sLine = oFS.ReadLine();
}
}
}
finally
{
// Cerrar el stream
oFS.Close();
}

dtIniBd = DateTime.Now;

// Guardar en bd
if ( dsLg.Logs.Count > 0 && duplicado == 0)
{
//Dalc dac = New Dalc();
StatusBar1.Text += ". Se está actualizando la base de datos. Espera un momento por favor. Esta operacion puede durar varios minutos.";
try
{
_dac.UpdateLogs(dsLg);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

if (duplicado == 0)
{
dtFi = DateTime.Now;

ts = new TimeSpan(dtIniBd.Ticks - dtIniFile.Ticks);
StatusBar1.Text += " (duration File:" + ts.ToString() + ")";

ts = new TimeSpan(dtFi.Ticks - dtIniBd.Ticks);
StatusBar1.Text += " (duration BD:" + ts.ToString() + ")";

ts = new TimeSpan(dtFi.Ticks - dtIniFile.Ticks);
StatusBar1.Text += " (duration Total:" + ts.ToString() + ")";

// msg
if (numImpContOk == 0)
{
MessageBox.Show("No se han importado datos");
}
else
{
MessageBox.Show("Se han importado datos");
}
}
else
{
MessageBox.Show("No se han importado datos debido a que ha intentado introducir datos duplicados");
}
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Volcar un csv a una bd sql

Publicado por Javier Suero (17 intervenciones) el 17/08/2007 11:32:46
Hola, Pablo,

¿por qué no usas los paquetes dts del sql server? Seguramente te dan un mejor rendimiento.

Un saludo, Javier.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Volcar un csv a una bd sql

Publicado por juan (1 intervención) el 18/06/2008 22:02:52
que paja
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar