gpt4 book ai didi

C# - 无法提交对 Access DB 的更改

转载 作者:搜寻专家 更新时间:2023-10-30 23:19:42 24 4
gpt4 key购买 nike

我正在处理一个 Windows 窗体项目,该项目要求我连接到一个 Access 数据库并浏览记录,然后添加/删除它们。我在网上看了一些教程,并认为我正确地遵循了它们。无论如何,我可以添加一个新项目,它会在窗口中正常显示,但在我退出后,所有更改都将丢失,并且数据库根本不会保存。

如有任何建议,我们将不胜感激。以下是我用来在按下按钮时保存数据库的代码。为了测试目的,我还硬编码了一些测试值。

    private DataSet data;
private int inc;
private int MaxRows;
private OleDbConnection connect;
private OleDbDataAdapter da;

/**
* Autoloads the first item into our form's text fields.
*/
private void BookMgmt_Load(object sender, EventArgs e)
{
data = new DataSet();
connect = new System.Data.OleDb.OleDbConnection();
connect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.\\LibraryAppDB.accdb";
string Books = "SELECT * FROM Books";
da = new OleDbDataAdapter(Books, connect);
connect.Open();
da.Fill(data, "Books");
Navigate();
MaxRows = data.Tables["Books"].Rows.Count;
connect.Close();
connect.Dispose();
}

/**
*changes data within the array update form with current
*item's info
*/
private void Navigate()
{
ID = data.Tables["Books"].Rows[inc];
textBox1.Text = ID.ItemArray.GetValue(0).ToString();
textBox2.Text = ID.ItemArray.GetValue(1).ToString();
textBox3.Text = ID.ItemArray.GetValue(2).ToString();
textBox5.Text = ID.ItemArray.GetValue(3).ToString();
textBox6.Text = ID.ItemArray.GetValue(4).ToString();
textBox7.Text = ID.ItemArray.GetValue(7).ToString();
textBox8.Text = ID.ItemArray.GetValue(8).ToString();
textBox10.Text = ID.ItemArray.GetValue(5).ToString();
textBox11.Text = ID.ItemArray.GetValue(6).ToString();


}

/**
* Saves the new element added into our actual database
*/
private void saveButton_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb;
DataRow dRow = data.Tables["Books"].NewRow();
cb = new OleDbCommandBuilder(da);
dRow[0] = 11;
dRow[1] = "test";
dRow[2] = "test";
dRow[3] = "test";
dRow[5] = "test";
dRow[6] = "test";
dRow[7] = "test";
dRow[8] = "test";

data.Tables["Books"].Rows.Add(dRow);
data.AcceptChanges();
da.Update(data, "Books");
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
Navigate();

MessageBox.Show("Entry Added", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

/**
* Deletes the current item displayed on the form
*/
private void deleteButton_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb;
cb = new OleDbCommandBuilder(da);
if (textBox1.Text == "1")
{
}
else
{
data.Tables["Books"].Rows[inc].Delete();
this.MaxRows--;
this.inc = 0;
Navigate();
data.AcceptChanges()
da.Update(data, "Books");
MessageBox.Show("Gone");
}

最佳答案

data.AcceptChanges() 将已修改记录和新记录的 RowState 重置为未更改,并从数据集中删除已删除的记录。通过在更新之前调用它,您实际上是在告诉 DataAdapter“这里无事可做”

只需将接受更改的调用移动到更新调用之后。这个调用很重要,因为这样后续的更新调用就不会尝试再次进行更改

关于C# - 无法提交对 Access DB 的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003601/

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