1 回答

TA貢獻1784條經(jīng)驗 獲得超7個贊
您通過向數(shù)據(jù)表添加新列來修改數(shù)據(jù)表的結(jié)構(gòu),這不會反映在生成的更新/插入/刪除 sql 命令中。
看看這個例子:OleDbCommandBuilder Class
很簡單:
adapter.Update(table);
只更新服務(wù)器中基表中的數(shù)據(jù)(如果有變化)
1)我期望有什么問題嗎?
不,它正在工作,但 MS 訪問中的基表結(jié)構(gòu)沒有變化
2)哪個參數(shù)沒有值?
你沒有在 SQL 命令中傳遞參數(shù)
3) 適配器、構(gòu)建器...是否按正確順序放置?
是的,但刪除修改數(shù)據(jù)表的部分。它沒有效果
4) 我有沒有其他事情要做,比如調(diào)用一個函數(shù)來更新帶有適配器的 SQL 命令?
用評論查看我的代碼。
5) 我怎樣才能改進我解決這個問題的方式?例如:有沒有什么事件可以幫助我更多地了解正在發(fā)生的事情?如何捕捉這樣的事件?
您不能通過添加新列來修改數(shù)據(jù)表的結(jié)構(gòu)
更新
我測試了你的代碼,用注釋修改了它:
public bool AddColumnOfString_ToDataTable(string tableName, string newColumnName, string defaultCellValue)
{
// Approach: Accessing database at minimum time.
// returns true if column name could not be found and column could be added
DataTable table = new DataTable();
//string strSQL = "SELECT " + tableName; // not valid syntax
string strSQL = "SELECT * from " + tableName;
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, myConnectionString);
adapter.Fill(table);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
bool result = false;
// remove this code, it has no effect on the underlying base table in MS Access databas
//any change in the structure of datatable has no effect on the database
/*
if (false == table.HasColumn(newColumnName))
{
DataColumn newColumn = new DataColumn(newColumnName, typeof(System.String));
newColumn.DefaultValue = defaultCellValue;
table.Columns.Add(newColumn);
result = true;
}
*/
// code to modify data in DataTable here
//Without the OleDbCommandBuilder this line would fail
adapter.Update(table);
//just to review the generated code
Console.WriteLine(builder.GetUpdateCommand().CommandText);
Console.WriteLine(builder.GetInsertCommand().CommandText);
return result;
}
更新2:
如果您有興趣向 MS Access 數(shù)據(jù)庫添加新列,可以運行以下代碼:
public bool AddColumn(OleDbConnection con,
string tableName,string colName,string colType, object defaultValue)
{
string query = $"ALTER TABLE {tableName} ADD COLUMN {colName} {colType} DEFAULT {defaultValue} ";
var cmd = new OleDbCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Sql Executed Successfully");
return true;
}
catch (OleDbException e)
{
Console.WriteLine("Error Details: " + e);
}
finally
{
Console.WriteLine("closing conn");
con.Close();
}
return false;
}
public void AddColumnTest()
{
OleDbConnection con = new OleDbConnection(myConnectionString);
string tableName="table1";
string colName="country";
string colType="text (30)";
object defaultValue = "USA";
AddColumn(con, tableName, colName, colType, defaultValue);
}
我用 MS Access 測試了代碼,它工作正常。
- 1 回答
- 0 關(guān)注
- 254 瀏覽
添加回答
舉報