当需要更新MSAccess表中的多个字段时(例如Salary = Salary * Factor,SomeNumber = GetMyBusinessRuleOn(SomeNumber)等...),更新应该影响表中的每条记录,你会选择哪种技巧使用?
我刚刚开始使用DataSet实现此功能,但卡住了(Updating and persisting dataset problem)
但也许这甚至不是处理这种批量更新的理想方式?
注意:更新不必首先在断开连接的数据上,因此不需要数据集。
更新:
答案 0 :(得分:1)
我只使用ODBCConnection / ODBCCommand并使用SQL Update查询。
您应该可以使用JET数据库驱动程序使用ODBCConeection对象建立与MSAccess数据库的数据库连接。
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\\PathTo\\Your_Database_Name.mdb; User Id=admin; Password=";
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// Suppose you wanted to update the Salary column in a table
// called Employees
string sqlQuery = "UPDATE Employees SET Salary = Salary * Factor";
OdbcCommand command = new OdbcCommand(sqlQuery, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
您可以使用这些网站来帮助您生成连接字符串:
编辑 - 使用数据阅读器循环记录以适应业务规则的示例
我应该注意,可以通过某些方式改进以下示例(特别是如果数据库驱动程序支持参数化查询)。我只是想举一个相对简单的例子来说明这个概念。
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
int someNumber;
int employeeID;
OdbcDataReader dr = null;
OdbcCommand selCmd = new OdbcCommand("SELECT EmployeeID, SomeNumber FROM Employees", connection);
OdbcCommand updateCmd = new OdbcCommand("", connection);
try
{
connection.Open();
dr = selCmd.ExecuteReader();
while(dr.Read())
{
employeeID = (int)dr[0];
someNumber = (int)dr[1];
updateCmd.CommandText = "UPDATE Employees SET SomeNumber= " + GetBusinessRule(someNumber) + " WHERE employeeID = " + employeeID;
updateCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Don't forget to close the reader when we're done
if(dr != null)
dr.Close();
}
// The connection is automatically closed when the
// code exits the using block.
}
答案 1 :(得分:0)