1

我已经设置了所有其他内容,但现在我只需要在访问中的表中添加一个条目。只需在数据网格视图中显示我的数据并使用带有绑定导航器的绑定源很简单,但我这里是场景:我有表,一个有 Song Name , Artist 和 Genre ,另一个只有流派的表,这两个表与流派有关系(具有参照完整性)。我想在 C# 程序中调用一个输入框来简单地将新流派添加到流派表中。现在由于没有数据网格视图或任何其他控件可以轻松添加条目,那么在表格中添加条目的简单过程是什么?

到目前为止,这是我用于适当事件处理程序的代码:

private void newGenreToolStripMenuItem_Click(object sender, EventArgs e)
{
    //(cnSongs)Connection delacred and instantiated elsewhere
    cnSongs.Open();

    string input = Interaction.InputBox("Genre ", "New Genre", "Type genre here", -1, -1);

    string InsertSql = "INSERT INTO tblGenres (Genre) VALUES (" + input + ")";

    OleDbCommand cmdInsert = new OleDbCommand(InsertSql, cnSongs);

    //(daSongs)Data Adapter delacred and instantiated elsewhere
    daSongs = new OleDbDataAdapter(InsertSql, cnSongs);

    daSongs.InsertCommand = cmdInsert;

    cmdInsert.ExecuteNonQuery();
    cnSongs.Close();
}

我做了研究,只得到了需要的 sql 语句,这很有用,但我需要知道如何在代码中执行它。

感谢您的时间。

4

1 回答 1

1

这是一个如何使用的示例OleDbParameter。但是,我不明白为什么您的代码不会产生新的流派。

private void newGenreToolStripMenuItem_Click(object sender, EventArgs e)
{
    //(cnSongs)Connection delacred and instantiated elsewhere
    cnSongs.Open();
    try {

        string input = Interaction.InputBox("Genre ", "New Genre", "Type genre here", -1, -1);

        Console.WriteLine("User input " + input);
        string InsertSql = "Insert Into tblGenres (Genre) Values (?)";

        OleDbCommand cmdInsert = new OleDbCommand(InsertSql, cnSongs);

        cmdInsert.Parameters.Add(new OleDbParameter("genre", input));

        int i = cmdInsert.ExecuteNonQuery();
        Console.WriteLine("Inseted " + i.toString() + " row(s)");
    } finally {
        cnSongs.Close();
    }
}
于 2013-09-22T15:57:28.690 回答