Query works in database but not via code

2
using (var cnx = new OleDbConnection(new AdministradorDAO().conexao))
            {
                var sql =
            @"insert into usuarios(matricula, nome, senha, nivel, maleta, email) 
            values (@matricula, @nome, @senha, @nivel, @maleta, @email)";


                using (var cmd = new OleDbCommand(sql, cnx))
                {
                    cnx.Open();

                    cmd.Parameters.AddWithValue("@matricula", txt_matricula.Text);
                    cmd.Parameters.AddWithValue("@nome", txt_nome.Text);
                    cmd.Parameters.AddWithValue("@senha", txt_senha.Text);
                    cmd.Parameters.AddWithValue("@nivel", DropDownList_nivel.Text);
                    cmd.Parameters.AddWithValue("@maleta", txt_maleta.Text);
                    cmd.Parameters.AddWithValue("@email", txt_email.Text);

                    try { cmd.ExecuteNonQuery(); }
                    catch { }
                    finally { if (cnx.State == ConnectionState.Open) cnx.Close(); }
                }
            }

When inserting directly into the seat, it runs perfectly

insert into actweb.usuarios (matricula, nome, senha, nivel, maleta, email) values ('TESTE', 'Frederico', 'TESTE', 1, 7000, '[email protected]'); 

I'm running directly, without using the right parameters.

  

var sql = @ "insert into users (id, name) values (ID_USUARIOS.nextval, 'Will work')";

    
asked by anonymous 16.09.2014 / 22:42

1 answer

4

There are two things wrong with your code:

  • try with catch empty;
  • As I recall, the syntax for insertion into Oracle does not start with @ , but rather with colon;

The correct one would look something like this:

using (var cnx = new OleDbConnection(new AdministradorDAO().conexao))
{
    var sql =
        @"insert into usuarios(matricula, nome, senha, nivel, maleta, email) 
        values (:matricula, :nome, :senha, :nivel, :maleta, :email)";

    using (var cmd = new OleDbCommand(sql, cnx))
    {
        cnx.Open();

        cmd.Parameters.AddWithValue("matricula", txt_matricula.Text != "" ? txt_matricula.Text : DbValue.Null);
        cmd.Parameters.AddWithValue("nome", txt_nome.Text);
        cmd.Parameters.AddWithValue("senha", txt_senha.Text != "" ? txt_senha.Text : DbValue.Null);
        cmd.Parameters.AddWithValue("nivel", DropDownList_nivel.Text != "" ? DropDownList_nivel.Text : DbValue.Null);
        cmd.Parameters.AddWithValue("maleta", txt_maleta.Text != "" txt_maleta.Text : DbValue.Null);
        cmd.Parameters.AddWithValue("email", txt_email.Text != "" ? txt_email.Text : DbValue.Null);

        try 
        { 
            cmd.ExecuteNonQuery(); 
        }
        catch (Exception e) 
        {
            throw; 
        }
        finally 
        { 
            if (cnx.State == ConnectionState.Open) cnx.Close(); 
        }
    }
}
    
17.09.2014 / 03:23