簡體   English   中英

將記錄添加到 c# 中的 Access 2007 數據庫時出現異常

[英]Exception when adding a record to an Access 2007 database in c#

我正在嘗試使用 c# 將記錄添加到 Access 2007 數據庫,但出現異常。

這是我的代碼,數據庫稱為hms ,表稱為login

DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");

你到底得到了什么錯誤信息。 猜測我會說您正在請求一個不存在的表,您的查詢僅返回 1 個表,因此它的索引將為 0

嘗試這個:

dRow = ds.Tables[0].NewRow();

據我所知,您的代碼的問題在於您創建了 DataSet ( ds ),但從不填充它。

你需要類似的東西:

using (OleDbConnection con = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\hms.mdb"))
{
    con.Open();
    string sql = "select * from login";
    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);

        DataRow dRow = ds.Tables[0].NewRow();
        dRow[1] = "sakest";
        ds.Tables["hms"].Rows.Add(dRow);
        da.Fill(ds, "hms");
        da.Update(ds, "hms");

        MessageBox.Show("new enrtry ");
    }
}

基本上,您所追求的是da.Fill(ds)行,以及從ds.Tables[1].NewRow()ds.Tables[0].NewRow()的變化。

注意:我重新調整了代碼,以便向您展示如何將OleDbConnectionOleDbDataAdapter包裝在using中,以確保它們被 CLR 正確清理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM