Unable to insert data in Access database using OleDb and C#

  • Thread starter Thread starter patr1c1a
  • Start date Start date
P

patr1c1a

Guest
I'm using C# (on Visual Studio 2013) with .Net 4.0 and an Access 2002 database (.mdb). I'm trying to insert some data but I get a "parameter has no default value" error which I don't understand.

The data I'm trying to insert is stored in these variables:

int cantidad = int.Parse(txtCantParejas.Text);
DateTime fechaActual = DateTime.Now;
int dia = fechaActual.Day;
int mes = fechaActual.Month;
int anio = fechaActual.Year;
int hora = fechaActual.Hour;
int minuto = fechaActual.Minute;

And this is my query:

string query = "INSERT INTO Torneo (cantParejas,dia,mes,anio,hora,minuto) VALUES (@cantParejas,@dia,@mes,@anio,@hora,@minuto)";



I've also tried with anonymous parameters but I get the same error:

string query = "INSERT INTO Torneo (cantParejas,dia,mes,anio,hora,minuto) VALUES (?,?,?,?,?,?)";



I have a connection string (connection test succeeds) stored in the variable "strDeConexion".

I then built the connection and command objects:

OleDbConnection dbConnection = new OleDbConnection(strDeConexion);
OleDbCommand commandStatement = dbConnection.CreateCommand();
commandStatement.CommandText=query;

And here's my insertion:

try {
dbConnection.Open();
commandStatement.Parameters.Add("cantParejas", OleDbType.Integer, cantidad);
commandStatement.Parameters.Add("dia", OleDbType.Integer, dia);
commandStatement.Parameters.Add("mes", OleDbType.Integer, mes);
commandStatement.Parameters.Add("anio", OleDbType.Integer, anio);
commandStatement.Parameters.Add("hora", OleDbType.Integer, hora);
commandStatement.Parameters.Add("minuto", OleDbType.Integer, minuto);

commandStatement.ExecuteNonQuery();
dbConnection.Close();
MessageBox.Show("Insertado OK");
}
catch (Exception e) {
MessageBox.Show(e.Message);
}

When running it, I get an exception saying that "Parameter @cantParejas has no default value".

Since this parameter is being assigned the variable "cantidad" which I get at the very beginning of the execution, I added breakpoints and made sure that "cantidad" wasn't null, and it isn't.

I do have one more column in my database: the first column is the primary key, called "idTorneo" and set as a not-null autoincrement. But I've read it's not necessary to add it in the insertion query because it should work automatically.

So I'm kind of lost here. Any help will be appreciated :)

Continue reading...
 
Back
Top