Short background: I am replacing an outdated, Visual Based based program with a C#-based one. With the program comes an Access (JET) based database which is already in use. For now, I want to connect to the current database for practical reasons. However in the foreseeable future I'd like to replace it with SQL Server.
Question: The database stores financial information using the Access 'Currency' datatype. In C#, I use 'Decimal' to represent financial information. Naturally, I get an error when I try an INSERT or UPDATE-query to store the Decimal in the Currency-field (actually, I get an error once and with it, it automatically changes the datatype of that specific record to Decimal). I'm not sure what the best way to solve this problem is:
Thanks in advance!
The exact error message:
System.Data.Odbc.OdbcException (0x80131937): ERROR [07006]
[Microsoft][ODBC Microsoft Access-stuurprogramma]Inbreuk op kenmerk van beperkt gegevenstype
It's Dutch and translates to Restricted data type attribute violation
My UPDATE code:
public Boolean setFuelCosts(int rentID, Decimal fuelcosts)
{
string conString = lem2;
string queryString = "UPDATE rental SET fuel = ? WHERE rentid = ?";
OdbcCommand command = new OdbcCommand(queryString);
command.Parameters.Add("@fuel", OdbcType.Decimal).Value = fuelcosts;
command.Parameters.Add("@rentid", OdbcType.Int).Value = rentID;
return factory.executeUpdateCommand(conString, command);
}
public Boolean executeUpdateCommand(String conString, OdbcCommand command)
{
bool result = false;
using (OdbcConnection connection = new OdbcConnection(conString))
{
try
{
command.Connection = connection;
command.CommandType = CommandType.Text;
connection.Open();
int i = command.ExecuteNonQuery();
result = (i >= 1);
connection.Close();
}
catch (Exception exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
System.Windows.Forms.MessageBox.Show(exc.StackTrace);
}
}
return result;
}
Your issue appears to be a limitation of the Access ODBC driver when dealing with Currency
fields using System.Data.Odbc
in .NET. An OdbcDataReader will return those fields as System.Decimal
(if the value is not NULL), but System.Data.Odbc
apparently won't accept a System.Decimal
parameter for a Currency
field.
As a workaround you could replace
command.Parameters.Add("@fuel", OdbcType.Decimal).Value = fuelcosts;
with
command.Parameters.Add("@fuel", OdbcType.NVarChar).Value = fuelcosts.ToString("0.0000");
I just tested this from C# 2010 against an Access 2000 database file and it worked for me.
User contributions licensed under CC BY-SA 3.0