使用SQLiteDataAdapter检索/插入数据

时间:2013-05-04 12:35:15

标签: c# system.data.sqlite

我目前正在使用Windows Forms和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,链接和数据库。 UI只会在用户交互时显示数据和引发事件。 Link创建数据库和SQLiteDataAdapter,通过上述方法检索数据表,并将其绑定到UI上的数据网格视图。用户不能通过数据网格视图更改表,但应通过某些文本框进行更改。 (这是否会将表绑定到dgv obosolete?)

使用适配器将用户输入文本框到数据库的最佳方法是什么?或者我应该使用DataReader和一些Insert方法而不是适配器吗?

据了解,UI通过Get-methods公开其控件。有更好的解决方案吗?

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(...)?
}

干杯!

1 个答案:

答案 0 :(得分:3)

INSERT,UPDATE和DELETE操作是DbCommand的工作。您需要一个不同的方法来获取用于INSERT的sql字符串和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注入。