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.