[英]Exception when adding a record to an Access 2007 database in c#
I'm trying to add a record to an Access 2007 database using c# but I get an exception.我正在尝试使用 c# 将记录添加到 Access 2007 数据库,但出现异常。
Here's my code, the database is called hms
and the table is called login
这是我的代码,数据库称为
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 ");
What error message are you getting exactly.你到底得到了什么错误信息。 At a guess I would say that you are requesting a table that does not exist, your query only returns 1 table so it's index would be 0
猜测我会说您正在请求一个不存在的表,您的查询仅返回 1 个表,因此它的索引将为 0
Try this:尝试这个:
dRow = ds.Tables[0].NewRow();
As far as I can tell, the issue with your code is that you create your DataSet ( ds
), but never fill it.据我所知,您的代码的问题在于您创建了 DataSet (
ds
),但从不填充它。
You need something similar to this:你需要类似的东西:
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 ");
}
}
Basically, the bit you're after is the da.Fill(ds)
line, and the change from ds.Tables[1].NewRow()
to ds.Tables[0].NewRow()
.基本上,您所追求的是
da.Fill(ds)
行,以及从ds.Tables[1].NewRow()
到ds.Tables[0].NewRow()
的变化。
Note: I've re-jigged the code so as to show you how to wrap the OleDbConnection
and OleDbDataAdapter
in using
's so as to ensure that they're cleaned up by the CLR properly.注意:我重新调整了代码,以便向您展示如何将
OleDbConnection
和OleDbDataAdapter
包装在using
中,以确保它们被 CLR 正确清理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.