[英]SQL connection selecting row to delete
I've got a local db in visual studio and in my project i want to delete a row wich is selected in the WPF.我在 Visual Studio 中有一个本地数据库,在我的项目中,我想删除在 WPF 中选择的行。
This is what i've got so far:这是我到目前为止所得到的:
private void Delete(object sender, RoutedEventArgs e)
{
DataRowView o = (DataRowView)g2.SelectedItem;
int ID = Convert.ToInt32(o.Row.ItemArray[0]);
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=MYFOLDER";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("DELETE FROM [STOCK] WHERE o = @ID", con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
{
MessageBox.Show("Row deleted");
}
In this statement i can select a row:在这个语句中,我可以 select 一行:
DataRowView o = (DataRowView)g2.SelectedItem; DataRowView o = (DataRowView)g2.SelectedItem; int ID = Convert.ToInt32(o.Row.ItemArray[0]);
int ID = Convert.ToInt32(o.Row.ItemArray[0]);
But then i have to delete it from my local db and i don't know how to complete this.但后来我必须从我的本地数据库中删除它,我不知道如何完成这个。 I know this statement is wrong...but what is the right one: cmd = new SqlCommand("DELETE FROM [STOCK] WHERE o = @ID", con);
我知道这句话是错误的……但正确的是什么: cmd = new SqlCommand("DELETE FROM [STOCK] WHERE o = @ID", con);
Hope anybody can help me.希望有人可以帮助我。 I'm using visual studio 2019 - it's a WPF project with C#.
我正在使用 Visual Studio 2019 - 这是一个 WPF 项目,带有 C#。
Greetings!问候!
You would need to refer to the ID
column in your DELETE
您需要参考
DELETE
中的ID
列
Note also the following另请注意以下事项
AttachDbFilename
is a bad idea , instead attach the database normally, using FOR ATTACH
AttachDbFilename
是个坏主意,而是使用FOR ATTACH
正常附加数据库using
using
处理连接和命令等对象try
catch
try
catch
处理错误private void Delete(object sender, RoutedEventArgs e)
{
DataRowView o = (DataRowView)g2.SelectedItem;
int ID = Convert.ToInt32(o.Row.ItemArray[0]);
try
{
const string query = @"
DELETE FROM [STOCK] WHERE [STOCK].Id = @ID;
";
using (SqlConnection con = new SqlConnection(Properties.ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Row deleted");
}
catch(Exception ex)
{
MessageBox.Show("Error occurred:\r\n" + ex.Message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.