I am updating a database using System.Data.Odbc.OdbcDataAdapter
. I also don't know what table or fields I'm updating until runtime. The code I have works and is roughly equivalent to the following:
{
mConn = new OdbcConnection(connectionStr);
mConn.Open();
mDataSet = new DataSet();
mDataAdapter = new OdbcDataAdapter(selectStatement, mConn);
mCmdBldr = new OdbcCommandBuilder(mDataAdapter);
var trans = mConn.BeginTransaction();
mDataAdapter.SelectCommand.Transaction = trans;
mDataAdapter.Fill(mDataSet, tableName);
mDataTable = mDataSet.Tables[tableName];
mDataTable.Rows.Add(mNewDataTableRow);
mDataAdapter.Update(mDataSet, tableName);
trans.Commit();
}
The above is stripped down from my actual code, but hopefully gives an idea of how I'm using the DataAdapter. As I say, it works, for the most part...
It does of course fail if I try to insert to many characters into a SQL Server VARCHAR column, in which case I get the following error (in this case, I'm writing to SQL Server, but the database could be something else):
System.Data.Odbc.OdbcException occurred HResult=0x80131937
Message=ERROR [22001] [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data would be truncated.
My question is this:
Is there any way in which I can get the OdbcDataAdapter
to automatically truncate text fields?
I understand I can turn off ANSI_WARNINGS in the database if I'm using SQL Server, but I might not be, and I don't want to do that anyway because in most cases I would want the above exception to be thrown. I also understand that I can inspect the constraints on the fields myself and truncate the data before I insert it, but I'm looking for something less manual. I'll write that code if I have to, but I'd rather not have to.
I've looked at setting the OdbcParameter.Size
property, but this simply throws an exception in a different place. Similarly with DataColumn.MaxLength
.
I've also looked at setting DataSet.EnforceConstraints
, but that doesn't prevent the above error when actually updating.
User contributions licensed under CC BY-SA 3.0