我对我的问题有疑问。通过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();
}
}
感谢您的帮助
答案 0 :(得分: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();
}