Question

I'm new with databases, and am making a point of sale using an Access 2007 database with C#. I've got the following method:

public static OleDbCommand connect()
{
    try
    {
        string path = System.Environment.GetEnvironmentVariable("USERPROFILE");
        string cadena = @"Provider=Microsoft.ACE.OLEDB.12.0;Data   Source="+path+@"\Documents\VikingPOS.accdb";
        conexion = new OleDbConnection(cadena);
        conexion.Open();
        command = new OleDbCommand();
        command = conexion.CreateCommand();
        return command;

    }
    catch (OleDbException e)
    {
        MessageBox.Show("Error: {0}", e.Errors[0].Message);
        return null;
    }
}

So I've been inserting and updating the information of the tables this way:

OleDbCommand link = Conexion.connect();
link.CommandText = "UPDATE ordenes SET subtotal = " + subtotal + ",impuesto = " + impuesto + ",total = " + total + " WHERE id_mesa = " + id_mesa + " AND id_estado = 1";
link.ExecuteNonQuery();

or

OleDbCommand link = Conexion.connect();
link.CommandText = "INSERT INTO secciones(descripcion,fecha_insert) VALUES ('" + nombre + "',Date())";
link.ExecuteNonQuery();

But I've also seen that some people insert and update using the following syntax:

using (OleDbConnection myCon = new OleDbConnection(connectionString))
{
    try
    {
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "UPDATE ingredientes SET [descripcion]=?,[id_medida]=?,[id_categoria]=?,[costo]=?,[impuesto]=?,[precio_venta]=?,[existencia]=?,[fecha_insert]=? WHERE [id_ingrediente]=?";
        cmd.Parameters.AddWithValue("@descripcion", p.getNombre());
        cmd.Parameters.AddWithValue("@id_medida", p.getId_medida());
        cmd.Parameters.AddWithValue("@id_categoria", p.getId_categoria());
        cmd.Parameters.AddWithValue("@costo", p.getCosto());
        cmd.Parameters.AddWithValue("@impuesto", p.getImpuesto());
        cmd.Parameters.AddWithValue("@precio_venta", p.getPrecio_venta());
        cmd.Parameters.AddWithValue("@existencia", p.getExistencia());
        cmd.Parameters.AddWithValue("@fecha_insert", fechaHoy);
        cmd.Parameters.AddWithValue("@id_ingrediente", p.getId());
        cmd.Connection = myCon;
        myCon.Open();
        int x = cmd.ExecuteNonQuery();
        ...

So my question is, what are the benefits of passing the values as parameters using the "AddWithValue" method? The way I'm doing it is pretty simple but has worked perfectly so far, that's why I've kept doing it that way.

Was it helpful?

Solution

String cmd = "UPDATE ingredientes SET [descripcion]=?";

these are called Parameterised SQL Queries which avoids the SQL Injection Attacks.

When you use the sql statements by injecting value directly into the table columns there is a chance of misusing it for accessing/modifying your data.

now take an example of using normal SQL Query and see how the SQL Injection Attacks may happen

Example:

String cmd="UPDATE ingredientes SET [descripcion]='"+TextBox1.Text+"'";

letus assume that if user enters following command in TextBox

TextBox value = > "xyz;delete * from Users;"

now command looks like this

String cmd="UPDATE ingredientes SET [descripcion]=xyz;delete * from Users;";

the above command first Updates the table with given description xyz but also deletes the data from Users table

OTHER TIPS

1-Avoid SQL Injection

2-Code is cleaner

3-code is changeable

One major benefit is that it protects you from SQL Injection attacks.

For example, what if I put in the nombre field Bobby'; DROP TABLE secciones;--. If you don't sanitize the inputs properly, you could lose the entire table (depending on permissions).

So instead of you having to come up with your own sanitation routines for every input, if you simply use parameterized queries, you will be better protected.

Your question is why would one go for adding parameters rather than simply making a OLE DB string and forming SQL query. right?

The problem with generating the Query using string connection is: SQL injection. If you are making the code for multiple users or web page. Then, you have to use Parameters.Addvalue method to improve security. Moreover, the Parameters.Add values is more intuitive to a programmer.But if it is just a small project with few people involved then it is completely fine to use.

Please let me know if I am wrong.!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top