先上代码: public class DBO
{
public DataSet ds;
private OracleConnection conn;
private OracleDataAdapter da; public DBO()
{
try
{
ds = new DataSet();
conn = new OracleConnection("ConnectionString");
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
da = new OracleDataAdapter("SELECT * FROM TableName", conn);
da_directory.Fill(ds);
ds.Tables[0].TableName = "TableName";
conn.Close();
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
} public int UpdateDB()
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommandBuilder builder = new OracleCommandBuilder(da);
da.InsertCommand = builder.GetInsertCommand();
da.DeleteCommand = builder.GetDeleteCommand();
da.UpdateCommand = builder.GetUpdateCommand();
int result = da.Update(ds.Tables["TableName"]);
conn.Close();
return result;
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
throw ex;
}
}
}
业务层调用后,修改了ds中的数据,断点跟踪发现在da.Update(ds.Tables["TableName"])执行之前,修改的结果还在,执行也不报错,就是数据库中的数据没有更新。
{
public DataSet ds;
private OracleConnection conn;
private OracleDataAdapter da; public DBO()
{
try
{
ds = new DataSet();
conn = new OracleConnection("ConnectionString");
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
da = new OracleDataAdapter("SELECT * FROM TableName", conn);
da_directory.Fill(ds);
ds.Tables[0].TableName = "TableName";
conn.Close();
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
} public int UpdateDB()
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommandBuilder builder = new OracleCommandBuilder(da);
da.InsertCommand = builder.GetInsertCommand();
da.DeleteCommand = builder.GetDeleteCommand();
da.UpdateCommand = builder.GetUpdateCommand();
int result = da.Update(ds.Tables["TableName"]);
conn.Close();
return result;
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
throw ex;
}
}
}
业务层调用后,修改了ds中的数据,断点跟踪发现在da.Update(ds.Tables["TableName"])执行之前,修改的结果还在,执行也不报错,就是数据库中的数据没有更新。
da.InsertCommand = builder.GetInsertCommand();
da.DeleteCommand = builder.GetDeleteCommand();
da.UpdateCommand = builder.GetUpdateCommand();
将此代码调整到dbo()中
ds.AcceptChanges();//add
是不是用代码直接修改ds.Tables[].Rows[][]这样做是错的?
da.InsertCommand = builder.GetInsertCommand();
da.DeleteCommand = builder.GetDeleteCommand();
da.UpdateCommand = builder.GetUpdateCommand();
这三句可以不要,要保证你查询的表有主键。da.Update(ds.Tables["TableName"])之后调用一下ds.AcceptChanges()试试。
业务层调用DBO的时候,每次修改完都多写了一个dbo.AcceptChanges(),这样没有更新数据库,但所有的行都变成了“UnChanged”……
折腾了一下午就因为这个……晕倒了……
谢谢大家,结帖!
只要数据没改错,怎么改都行。你看看你的表有没有主键,如果没有主键就定义一个,如果不能定义主键就不要用OracleCommandBuilder,而是手动指定InsertCommand、DeleteCommand和UpdateCommand。