0

我对我的问题有疑问。当我单击正确的选项时,通过 form1 中的 manustrip,我创建了新的 form2。此表单用于删除访问数据库中的数据,如果您选择行的组合框 ID,它将删除 ID 4 或其他内容的整行...我的组合框已连接到我的数据库。我的代码:

public partial class Form2 : Form
{
    public string myConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bojan\Desktop\Programiranje\School\Novo\Novo\Ure.accdb";  // to je provider za Access 2007 in več - če ga ni na lokalni mašini ga je treba namestiti!!!

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'dataSet1.Ure' table. You can move, or remove it, as needed.
        this.ureTableAdapter.Fill(this.dataSet1.Ure);
    }

    private void Brisanje_Click(object sender, EventArgs e)
    {
        OleDbConnection myConnection = null;

        myConnection = new OleDbConnection();                      // kreiranje konekcije
        myConnection.ConnectionString = myConnectionString;
        myConnection.Open();

        OleDbCommand cmd = myConnection.CreateCommand();
        cmd.Connection = myConnection;
        cmd.CommandText = "DELETE FROM Ure WHERE (ID) = '"+Izbor.SelectedValue+"'";
        cmd.ExecuteNonQuery();
        cmd.Prepare();
        myConnection.Close();
    }
}

谢谢你的帮助

4

1 回答 1

3

正如@musefan指出的那样,您确实应该使用参数化查询,另一个问题似乎是ID周围的单引号,这将导致数据类型不匹配错误。最后,您的连接和命令对象实现了 IDisposable,因此我建议将它们包装在 using 块中。

以下代码应该可以工作

using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
    var idParam = new OleDbParameter("@id", Izbor.SelectedValue);

    myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = @id";
    myCommand.Parameters.Add(idParam);

    myConnection.Open();
    myCommand.ExecuteNonQuery();
}
于 2013-11-11T09:49:59.060 回答