在简单的 WinForms 应用程序中管理数据访问

发布于 2024-10-09 02:32:25 字数 3133 浏览 0 评论 0原文

我有一个使用 SQLite 的简单 WinForms 数据输入应用程序。它将始终是单用户应用程序,并且始终具有本地数据库。我有多个选项卡,其中 UserControls 作为选项卡的内容。每次选择选项卡时,都会初始化相应的 UserControl,并删除旧的 UserControl(使用 TabPage.Controls.Remove)。

每个 UserControl 都会初始化一个通用 DataAccess 对象,该对象包装所有数据库内容,并且可以与任何选项卡内容一起重用。问题是我在选项卡(UserControl)的生命周期内有一个打开的 SQLiteConnection。我在其他地方读到这不是一个好的做法。我不想在设计上过度使用复杂的数据层和业务对象层,部分是因为我不知道如何做到这一点,部分是因为我认为这个应用程序没有必要。

我基本上在内存中保留相同的连接、适配器、DataTable、SqlCommand 等对象,然后使用不同的 sql 查询参数重用它们,并使用其他方法(如 RowCount)获取缓存的数据。我在使用 LoadData 方法时遇到问题,因为它没有清除 DataTable 中以前的查询结果,所以我一开始就手动执行此操作。

我尝试找出一种将“using”与 SQLiteConnection 和其他对象一起使用的方法,但随后我必须重做整个 DataLoad 内容或类似的内容来处理 RowCount 等简单的内容。所以我只是在寻找有关这种数据访问方法的建议和评论。

下面是我的 DataAccess 类。

public class DataAccess
{
    private SQLiteConnection connection = new SQLiteConnection(Global.DbConnectionString);
    private DataTable dataTable = new DataTable();
    private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
    private SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder();
    private SQLiteCommand command = new SQLiteCommand();
    private BindingSource bindingSource = new BindingSource();


    public DataAccess()
    {
        dataAdapter.SelectCommand = command;
        commandBuilder.DataAdapter = dataAdapter;
        bindingSource.DataSource = dataTable;
    }

    ~DataAccess()
    {
        connection.Dispose();
    }

    public BindingSource BindingSource
    {
        get { return bindingSource; }
    }


    ///*
    public void LoadData(string sql, Dictionary<string, string> parameters)
    {
        try
        {
            dataTable.Clear();
            command.Connection = connection;

            // Ignore sql parameter if we already have CommandText. This assumes sql never changes per instance
            if (command.CommandText == null)
                command.CommandText = sql;

            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                if (command.Parameters.Contains(parameter.Key))
                    command.Parameters[parameter.Key].Value = parameter.Value;
                else
                {
                    command.Parameters.Add(new SQLiteParameter(parameter.Key));
                    command.Parameters[parameter.Key].Value = parameter.Value;
                }
            }
            dataAdapter.Fill(dataTable);

        }
        catch (SqlException)
        {
            MessageBox.Show("Data Problem, need to display what's wrong later");
        }

    }//*/

    public int RowCount()
    {
        return dataTable.Rows.Count;
    }

    public string GetFieldValue(int row_index, string column_name)
    {
        return dataTable.Rows[row_index][column_name].ToString();
    }

    public void Save()
    {
        dataAdapter.Update(dataTable);
    }

    public void NewRow(Dictionary<string, string> fields)
    {
       DataRow dataRow = dataTable.NewRow();

        foreach (KeyValuePair<string, string> field in fields)
            dataRow[field.Key] = field.Value;

        dataTable.Rows.Add(dataRow);
    }
}

I have a simple WinForms data entry app that uses SQLite. It will always be a single-user app and always with a local database. I have multiple tabs, with UserControls serving as content for the tabs. Each time a tab is selected, an appropriate UserControl is initialized, and the old one is removed (using TabPage.Controls.Remove).

Each UserControl initializes a generic DataAccess object, which wraps all the database stuff and can be reused with any tab content. The issue is that I have an open SQLiteConnection for the duration of the life of the tab (UserControl). I've read elsewhere that it's not a good practice. I don't want to overkill on the design with elaborate data layers and business object layers, partly because I don't know how to do it, and partly because I don't think it's necessary for this app.

I'm basically keeping the same connection, adapter, DataTable, SqlCommand, etc objects in memory and just reusing them with different sql query parameters, and to get that cached data with other methods (like RowCount). I had a problem with LoadData method as it was not clearing out previous query results from DataTable, so I'm doing it manually in the beginning.

I tried figuring out a way to use "using" with SQLiteConnection and other objects, but then I'd have to redo the whole DataLoad stuff or similar for simple things like RowCount. So I'm just looking for suggestions and comments on this approach with data access.

Below is my DataAccess class.

public class DataAccess
{
    private SQLiteConnection connection = new SQLiteConnection(Global.DbConnectionString);
    private DataTable dataTable = new DataTable();
    private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
    private SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder();
    private SQLiteCommand command = new SQLiteCommand();
    private BindingSource bindingSource = new BindingSource();


    public DataAccess()
    {
        dataAdapter.SelectCommand = command;
        commandBuilder.DataAdapter = dataAdapter;
        bindingSource.DataSource = dataTable;
    }

    ~DataAccess()
    {
        connection.Dispose();
    }

    public BindingSource BindingSource
    {
        get { return bindingSource; }
    }


    ///*
    public void LoadData(string sql, Dictionary<string, string> parameters)
    {
        try
        {
            dataTable.Clear();
            command.Connection = connection;

            // Ignore sql parameter if we already have CommandText. This assumes sql never changes per instance
            if (command.CommandText == null)
                command.CommandText = sql;

            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                if (command.Parameters.Contains(parameter.Key))
                    command.Parameters[parameter.Key].Value = parameter.Value;
                else
                {
                    command.Parameters.Add(new SQLiteParameter(parameter.Key));
                    command.Parameters[parameter.Key].Value = parameter.Value;
                }
            }
            dataAdapter.Fill(dataTable);

        }
        catch (SqlException)
        {
            MessageBox.Show("Data Problem, need to display what's wrong later");
        }

    }//*/

    public int RowCount()
    {
        return dataTable.Rows.Count;
    }

    public string GetFieldValue(int row_index, string column_name)
    {
        return dataTable.Rows[row_index][column_name].ToString();
    }

    public void Save()
    {
        dataAdapter.Update(dataTable);
    }

    public void NewRow(Dictionary<string, string> fields)
    {
       DataRow dataRow = dataTable.NewRow();

        foreach (KeyValuePair<string, string> field in fields)
            dataRow[field.Key] = field.Value;

        dataTable.Rows.Add(dataRow);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_畞蕅 2024-10-16 02:32:25

如果您想做得很好,您应该创建一个数据访问层,该层将公开获取数据并修改数据的方法。该层将在必要时打开连接,然后关闭它。您可以在其顶部添加一个缓存层。你的 GUI 只会使用较低层的数据对象。

这不是一个小的重写,所以如果你当前的解决方案有效,并且你不想投入太多精力,那么就这样保留它,这也没有那么糟糕。如果它是一个简单的程序,那么这个简单的解决方案就可以了。

If you want to do it nicely, you should create a data access layer that would expose methods to fetch the data and modify it. This layer would open a connection whenever it's necessary and then close it. You could add a caching layer on top of it. And your GUI would only use the data objects from the lower layers.

It's not a small rewrite, so if your current solution works, and you don't want to put much effort into it, then just leave it like this, it's not that bad. If it's a simple program, then this simple solution is just fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文