我目前正在使用Windows窗体和SQLite创建一个小型应用程序。阅读一些教程后,我实现了这种方法来进行数据检索:

public DataTable GetDataTable(ref SQLiteDataAdapter adapter, string sql)
        {
            DataTable dt = new DataTable();

            // Connect to database.
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            // Create database adapter using specified query
            using (adapter = new SQLiteDataAdapter(sql, connection))
            // Create command builder to generate SQL update, insert and delete commands
            using (SQLiteCommandBuilder command = new SQLiteCommandBuilder(adapter))
            {
                // Populate datatable to return, using the database adapter
                adapter.Fill(dt);
            }
            return dt;
        }


(以及另一个不使用SQLiteDataAdapter作为参数的GetDataTable)

我有三个类,我们将它们称为UI,Link和Database。 UI除了显示数据并在用户交互时引发事件外什么也不做。链接创建数据库和SQLiteDataAdapter,通过上述方法检索数据表,并将其绑定到UI上的数据网格视图。用户无法通过数据网格视图更改表,但应通过某些文本框进行更改。 (这会使表绑定到过时的dgv吗?)

使用适配器将用户输入从文本框输入数据库的最佳方法是什么?还是应该使用DataReader和某些Insert方法代替适配器?

众所周知,UI通过Get方法公开其控件。有更好的解决方案吗?

private void Initialize()
{
    // Subscribe to userInterface events
    userInterface.DataGridViewSelectionChanged += new EventHandler(userInterface_DataGridViewSelectionChanged);
    userInterface.NewClicked += new EventHandler(userInterface_NewClicked);
    userInterface.SaveClicked += new EventHandler(userInterface_SaveClicked);

    // Get dataGridView from userInterface and bind to database
    bindingSource = new BindingSource();
    bindingSource.DataSource = database.GetDataTable(ref adapter, "SELECT * FROM SomeTable");
    userInterface.GetDataGridView().DataSource = bindingSource;
}

void userInterface_DataGridViewSelectionChanged(object sender, EventArgs e)
{
    if (userInterface.GetDataGridView().SelectedRows.Count != 0)
    {
        DataGridViewRow row = userInterface.GetDataGridView().SelectedRows[0];
        userInterface.GetIDTextBox().Text = row.Cells["PrimaryKey].Value.ToString();
        userInterface.GetOtherIDTextBox().Text = row.Cells["ForeignKey"].Value.ToString();

        DataTable dt = database.GetDataTable("SELECT * from SomeTable WHERE ForeignKey=" + row.Cells["ForeignKey"].Value);
        userInterface.GetLastNameTextBox().Text = dt.Rows[0]["LastName"].ToString();
        userInterface.GetFirstNameTextBox().Text = dt.Rows[0]["FirstName"].ToString();
        userInterface.GetCompanyTextBox().Text = dt.Rows[0]["Company"].ToString();
    }
}

void userInterface_NewClicked(object sender, EventArgs e)
{
    // Get all text boxes and clear them
    // Let the UI take care of this by itself?
}

void userInterface_SaveClicked(object sender, EventArgs e)
{
        // Get text/data from all text boxes and insert (or update if editing table) into database
        // adapter.Update(...)?
}


干杯!

最佳答案

INSERT,UPDATE和DELETE操作是DbCommand的工作。您需要使用sql字符串和用于INSERT的SQLiteParameter集合的其他方法。

我将尝试为INSERT操作编写一些伪代码

public class MyHelperClass
{
    public static int InsertCommand(string sql, SQLiteParameter[] parameters)
    {
        int result = 0;
        using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
        {
            cmd.Parameters.AddRange(parameters);
            result = cmd.ExecuteNonQuery();
        }
        return result;
    }
}


现在,您必须构建参数数组以传递给help方法,这应该从您的UI代码完成

string sqlCommand = "INSERT INTO table1 (FirstName, LastName) VALUES (@fName, @lName)";
SQLiteParameter[] p = new SQLiteParameter[2];
p[0] = new SQLiteParameter("@fName", TextBox1.Text);
p[1] = new SQLiteParameter("@lName", TextBox2.Text);
int rowAdded = MyHelperClass,InsertCommand(sql, p);


UPDATE和DELETE命令的操作类似。我也建议您添加一个接受参数数组的GetDataTable版本,而不是使用字符串连接构建sql命令。由于无数次重复在这里,字符串连接会导致错误,最糟糕的是,导致易受sql注入攻击的弱代码。

07-26 09:34
查看更多