gpt4 book ai didi

c# - 如何使用 oleDbDataAdapter.Update(myDataSet) 更新 excel 文件

转载 作者:行者123 更新时间:2023-12-04 22:09:53 28 4
gpt4 key购买 nike

我不断收到 InvalidOperationException(“当传递带有修改行的 DataRow 集合时,更新需要有效的 UpdateCommand”)。我只是无法弄清楚更新命令有什么问题。

这是我到目前为止的代码:

    OleDbConnection connection;
OleDbDataAdapter clientsAdapter new OleDbDataAdapter();
DataSet myDataSet = new DataSet();

public void Setup()
{
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Clients.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";";
connection = new OleDbConnection(connectionString);
connection.Open();


// SQL
clientsAdapter.SelectCommand = new OleDbCommand("SELECT * FROM [Clients$]", connection);
OleDbCommand updateCmd = new OleDbCommand(
"UPDATE [Clients$] " +
"SET " +
"[Family Name] = ?, " +
"[Given Name] = ?, " +
"Address = ?, " +
"[Home Phone] = ?, " +
"[Work Phone] = ?, " +
"[Mobile Phone] = ?, " +
"Email = ?, " +
"Status = ?, " +
"Comments = ? " +
"WHERE " +
"[Last Name] = ? AND " +
"[First Name] = ?"

// SET clause
updateCmd.Parameters.Add("Family Name", OleDbType.Char, 100, "Family Name");
updateCmd.Parameters.Add("Given Name", OleDbType.Char, 100, "Given Name");
updateCmd.Parameters.Add("Address", OleDbType.Char, 100, "Address");
updateCmd.Parameters.Add("Home Phone", OleDbType.Double, 100, "Home Phone");
updateCmd.Parameters.Add("Work Phone", OleDbType.Char, 100, "Work Phone");
updateCmd.Parameters.Add("Mobile Phone", OleDbType.Char, 100, "Mobile Phone");
updateCmd.Parameters.Add("Email", OleDbType.Char, 100, "Email");
updateCmd.Parameters.Add("Status", OleDbType.Char, 100, "Status");
updateCmd.Parameters.Add("Comments", OleDbType.Char, 100, "Comments");

// WHERE clause
OleDbParameter fName = updateCmd.Parameters.Add("Old Family Name", OleDbType.Char, 100, "Family Name");
fName.SourceVersion = DataRowVersion.Original;
OleDbParameter lName = updateCmd.Parameters.Add("Old Given Name", OleDbType.Char, 100, "Given Name");
lName.SourceVersion = DataRowVersion.Original;

clientsAdapter.InsertCommand = updateCmd;

// create table and fill
DataTable clients = new DataTable("Clients");
clientsAdapter.Fill(clients);
myDataSet.Tables.Add(clients);

connection.Close();
}

public void UpdateDb()
{
connection.Open();
clientsAdapter.Update(myDataSet, "Clients"); // errer occurs here
connection.Close();
}

虽然google上有几个简单的例子,但我一直没能找到解决方案。

最佳答案

你还没有设置UpdateCommand客户端适配器的属性。

您创建了一个 OleDbCommand称为“updateCmd”,但随后您已将 InsertCommand 属性设置为它:
clientsAdapter.InsertCommand = updateCmd;
我怀疑你想要:
clientsAdapter.UpdateCommand = updateCmd;

关于c# - 如何使用 oleDbDataAdapter.Update(myDataSet) 更新 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10535663/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com