In C#, when I insert a record into Access tabel, why will it cause error if the length of string
I define a field "myField" in the tabel "AccessTable", the length of "myField" is 3
when I insert a string with the length 7, it will cause error, why?
myCommand.CommandText="Insert into AccessTable (myField) values ('123457')"; //cause error!!!
myCommand.CommandText="Insert into AccessTable (myField) values ('12')"; //OK
When I do the same thing using Pascal in Delphi, if the length of string exceed the length of a field,
it will not cause error, the exceeded string will be trim automatically!
OleDbConnection myOleDbConnection=null;
OleDbTransaction trans=null;
myTreePar.myTreeView.BeginUpdate();
try
{
myOleDbConnection=ConstClass.GetDatabaseConnect();
myOleDbConnection.Open();
trans=myOleDbConnection.BeginTransaction();
OleDbCommand myCommand=new OleDbCommand();
myCommand.Connection=myOleDbConnection;
myCommand.Transaction=trans;
myCommand.CommandText="Insert into AccessTable (myField) values ('123457')";
myCommand.ExecuteNonQuery();
trans.Commit();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
trans.Rollback();
}
finally
{
myOleDbConnection.Close();
}
[1257 byte] By [
CUIWEI] at [2007-12-16]
It's so bother to check the length of string before insert record into table every time! Many times it's not very serious to discard the rest of string
without warning. but in C#, it will cause serious error, the whole program will be crashed. so I hope
the extra charcters can be discarded automatically, how can I do in C#!
I would turn this question the other way around. Rather than asking 'why does .NET warn me that I am about to lose data?' I would ask (in a Delphi forum, of course) 'why does Delphi *not* warn me that I am about to lose data?' . (If that really is the normal behaviour of Delphi.)
..NET is doing the right thing here. This is expected behaviour. If you want to ignore the error, you can do that, or better still, trim the string to the maximum length yourself before attempting to insert it. You could, if you wished, warn the user of the problem and let the user choose whether to trim the string or re-enter a different string. All of these choices are available to you only because .NET raises the error. No error, no choices.
-- Brendan Reynolds (Access MVP)
I dont know what you are doing in delphi, but my Delphi 7 doesnt truncate, but errors with code 8152 using ado or DBExpress components (dont know about bde/odbc)
Delphi blows vb6 away, by the way (vb6 was a dog. . . vb.7 is not much better)