删除ms访问数据库中的记录

时间:2015-07-26 02:33:44

标签: c#

我已使用此代码从MS Access数据库表中删除记录。程序运行成功,但数据库中的记录未被删除。

private void button3_Click_2(object sender, EventArgs e)
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        String query=" delete from [student table] where Name="+txtname.Text+"";
        command.CommandText= query;
       MessageBox .Show ("Data deleted");
        connection.Close();

    }

1 个答案:

答案 0 :(得分:0)

以下代码应该有效:

using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
    var nameParam = new OleDbParameter("@name", txtname.Text);

    myCommand.CommandText = "DELETE FROM [student table] WHERE (Name) = @name";
    myCommand.Parameters.Add(nameParam);

    myConnection.Open();
    myCommand.ExecuteNonQuery();
}