繁体   English   中英

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

[英]Using INSERT sql command with Access database in C#

我已经进行了其他所有设置,但是现在我只需要在access中向表中添加一个条目即可,只需在数据网格视图中显示我的数据并使用带有绑定导航器的绑定源就可以了,但是我这里是这种情况:我必须要有一个表,一个具有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语句,这很有用,但我需要知道如何在代码中执行它。

感谢您的时间。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM