-1

i need help with a little problem.

private void SaveButton_Click(object sender, EventArgs e)
{
    MemoryStream fingerprintData = new MemoryStream();
    Template.Serialize(fingerprintData);
    fingerprintData.Position = 0;
    BinaryReader br = new BinaryReader(fingerprintData);
    Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
    HL.RegistroHuella(ComboBx, LabelMs, bytes);
}

This is the save button...

public void RegistroHuella(ComboBox ComboBx, Label LabelMs, Byte[] bytes)
{
    try
    {
        string hola;
        ConexionHuella();
        hola = ComboBx.SelectedIndex.ToString();
        DbCommand = DbConnection.CreateCommand();
        DbCommand.CommandText = "SELECT * FROM HUELLAS WHERE ID = " + hola + "";
        DbReader = DbCommand.ExecuteReader();
        if (DbReader.Read())
        {
            LabelMs.Text = "El estudiante ya existe en la base de datos";
        }
        else
        {
            DbReader.Close();
            DbCommand.CommandText = "INSERT INTO HUELLAS VALUES('" + hola + "','" + bytes + "')";
            DbReader = DbCommand.ExecuteReader();
            if (DbReader.RecordsAffected > 0)
            {
                LabelMs.Text = "El estudiante ha sido registrado correctamente.";
            }
            else
            {
                LabelMs.Text = "Hubo un problema al momento de registrar a este usuario.";
            }
        }
        DbConnection.Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        //LabelMs.Text = ex.Message;
    }
}

The problem is the next... When i pressed the save button, the code generates a register in my odbc but in the field "Huella" didn't insert well.

The image: -> Problem

imsome1
  • 1,182
  • 4
  • 22
  • 37
Juan Molina
  • 65
  • 1
  • 8
  • You inserted the value of byte[].ToString(), that happens when you use the + operator. Google "dbcommand insert bytes" for hits, several existing SO posts talk about it. – Hans Passant Oct 12 '17 at 11:22
  • Nop, this solution is in sql. I use odbc. – Juan Molina Oct 12 '17 at 11:41
  • @JuanMolina - the .Net database commands for the various databases are very similar (by design). So while that solution is not a 100% fit, you might be able to adapt it (Use a `Db` prefix instead of `Sql`) – Hans Kesting Oct 12 '17 at 12:51

2 Answers2

2

Fixing the SQL Injection vulnerability in your code will also solve the problem with inserting the image data.

You should avoid storing connection and command objects in fields. Instead, they should be created as local variables, and wrapped in using statements to ensure that their resources are always cleaned up.

If you can't move the DbConnection field to a local variable yet, then you should call its Close method in a finally block.

You shouldn't call ExecuteReader on a command that isn't going to return any records - INSERT, UPDATE or DELETE commands. Instead, call ExecuteNonQuery, which returns the number of rows affected.

You also don't need to call ExecuteReader to test whether a record exists. Just select the ID of the first matching record, and use ExecuteScalar to return that value.

public void RegistroHuella(ComboBox ComboBx, Label LabelMs, Byte[] bytes)
{
    try
    {
        int hola = ComboBx.SelectedIndex;

        ConexionHuella();

        using (var command = DbConnection.CreateCommand())
        {
            command.CommandText = "SELECT TOP 1 ID FROM HUELLAS WHERE ID = ?";
            command.Parameters.AddWithValue("@hola", hola);

            if (command.ExecuteScalar() != null)
            {
                LabelMs.Text = "El estudiante ya existe en la base de datos";
                return;
            }
        }

        using (var command = DbConnection.CreateCommand())
        {
            command.CommandText = "INSERT INTO HUELLAS VALUES (?, ?)";
            command.Parameters.AddWithValue("@hola", hola);
            command.Parameters.AddWithValue("@bytes", bytes);

            int recordsAffected = command.ExecuteNonQuery();
            if (recordsAffected > 0)
            {
                LabelMs.Text = "El estudiante ha sido registrado correctamente.";
            }
            else
            {
                LabelMs.Text = "Hubo un problema al momento de registrar a este usuario.";
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        //LabelMs.Text = ex.Message;
    }
    finally
    {
        DbConnection.Close();
    }
}

NB: The OdbcCommand doesn't seem to work with named parameters. You have to use ? as the parameter placeholder, and ensure that the parameters are added to the collection in the same order as they appear in the query.

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
0

1st USE PARAMETERS, it is very important.

EDIT: (based on Richard Deeming comment)

DbCommand.CommandText = "INSERT INTO HUELLAS VALUES(@param1,@param2)";                
DbCommand.Parameters.Add("@param1",OdbcType.Text).Value = hola;
DbCommand.Parameters.Add("@param2",OdbcType.Image).Value = bytes;
int result = DbCommand.ExecuteNonQuery();
if (result> 0)
{
   LabelMs.Text = "El estudiante ha sido registrado correctamente ";
}
else
{
   LabelMs.Text = $"Hubo un problema al momento de registrar a este usuario";
}
apomene
  • 14,282
  • 9
  • 46
  • 72