简体   繁体   中英

Updating tables with column names containing @ symbols using OleDbCommandBuilder in C#

Greetings great SO comrades;

I'm trying to use this code to make changes to a SQL Server database:

adapter = new OleDbDataAdapter(
    Db.GetRecordSql(table.Name, recordId), Db.Connection);
OleDbCommandBuilder cmd = new OleDbCommandBuilder(adapter);
DataSet ds = new DataSet();
adapter.Fill(ds);

Then later, when saving changes made to a DataRow :

adapter.Update(new DataRow[] { row });

It works exactly the way I want it to work. The DB operations are all very simple, and the app supports multiple database formats, so this is the method that suits the task.

My problem is that this method fails when the row contains a column with an @ sign in its name. The database schema prefixes column names with an @ sign to denote private meta data, such as creation/modification dates and checksums.

When a column name contains an @ sign, the Update method throws an OleDbException :

Must declare the scalar variable @created

Great. Now what?

Seriously, I've googled this thing to death. I know it's a bit unusual to include an @ symbol in a column name, but that's the hand I've been dealt.

Any ideas? Pretty please? :)

You should be able to specify the QuotePrefix and QuoteSuffix characters in the command builder:

cmd.QuotePrefix = "[";
cmd.QuoteSuffix = "]";

After doing that, the command it builds will have brackets around all the names (columns and tables). And I suppose it goes without mentioning, but be sure that the prefix and suffix values you use are valid for the underlying database. For example, for some databases, it might be necessary to use double quotes instead of brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM