我使用DataTable/DataAdapter体系结构在数据库和我的模型对象之间进行调解。我的数据库中有两个表,dataGridView两个窗口中有两个表。起初,我调用GetData方法来填充我的第一个dataGridView. 已成功填充。然后我更改其中的任何字段并调用UpdateTableChanges. 更改的行也成功添加到 db 中。然后我GetData再次调用填充 second dataGridView,但没有返回任何行。GetData 第二次调用时也没有任何错误。但是,当我不调用UpdateTableChanges并GetData第二次调用时,所有行都会返回。方法后有一些问题UpdateTableChanges。感觉这个方法改变了我的一些数据_adapter。所有方法中的所有参数都是正确的,因为如果我不调用则返回行UpdateTableChanges. 适配器更新数据库后,我需要更改什么来获取行?任何帮助都会很棒。为了更好地理解,我删除了 try/catch 块。
class DBModel
{
private readonly string _connectionString;
private MySqlDataAdapter _adapter;
private MySqlConnection _connection;
public DBModel()
{
_connectionString = "SERVER = localhost; DATABASE = transportation; USER ID = root;";
_connection = new MySqlConnection(_connectionString);
_adapter = new MySqlDataAdapter(String.Empty, _connection);
}
public BindingSource GetData(string selectCommand)
{
var bindingSource = new BindingSource();
SetMySqlSelectCommand(selectCommand);
var commandBuilder = new MySqlCommandBuilder(_adapter);
var table = new DataTable();
_adapter.Fill(table);
bindingSource.DataSource = table;
return bindingSource;
}
public void UpdateTableChanges(BindingSource bindingSource, string selectCommand)
{
SetMySqlSelectCommand(selectCommand);
_adapter.Update((DataTable)bindingSource.DataSource);
}
private void SetMySqlSelectCommand(string selectCommand)
{
var mySqlCommand = _connection.CreateCommand();
mySqlCommand.CommandText = selectCommand;
_adapter.SelectCommand = mySqlCommand;
}