[英]C# and delete specific row in SQL Server database
My problem is I don't get any errors, but when I tried to delete specific data from the database, the system would just display Data Deleted
.我的问题是我没有收到任何错误,但是当我尝试从数据库中删除特定数据时,系统只会显示
Data Deleted
。
private void Delete_Click(object sender, EventArgs e)
{
string Query = "delete from dbo.student where C_ID=" + textBox1.Text;
cc.con = new SqlConnection(cs.DBConn);
cc.con.Open();
try
{
MessageBox.Show("Data Deleted");
}
catch
{
MessageBox.Show("User Not Deleted");
}
}
You need to actually create a SqlCommand
and execute the query, Also - to avoid SQL injection and other problems, please always use parametrized queries!您需要实际创建一个
SqlCommand
并执行查询,另外 - 为避免 SQL 注入和其他问题,请始终使用参数化查询!
Try something like this:尝试这样的事情:
private void Delete_Click(object sender, EventArgs e)
{
string delQuery = "DELETE FROM dbo.student WHERE C_ID = @ID";
try
{
using (SqlConnection conn = new SqlConnection(cs.DBConn))
using (SqlCommand cmdDel = new SqlCommand(delQuery, conn))
{
// define parameter and set value
cmdDel.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text);
// open connection, execute query, close connection
conn.Open();
int rowsDeleted = cmdDel.ExecuteNonQuery();
conn.Close();
// show success message
MessageBox.Show("Data Deleted");
}
}
catch
{
MessageBox.Show("User Not Deleted");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.