在 C# 中将 INSERT sql 命令与 Access 数据库配合使用

本文关键字:数据库 Access 中将 INSERT sql 命令 | 更新日期: 2023-09-27 18:32:15

我已经设置了其他所有内容,但现在我只需要在 Access 中向我的表添加一个条目。在数据网格视图中显示我的数据并使用带有绑定导航器的绑定源很简单,但我在这里是场景:我必须表,一个带有歌曲名称、艺术家和流派的表,另一个只有流派的表,这两个表与流派的关系(具有引用完整性)。我想在 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语句,这很有用,但我需要知道如何在代码中解释它。

谢谢你的时间。

在 C# 中将 INSERT sql 命令与 Access 数据库配合使用

这是如何使用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();
    }
}