简体   繁体   English

SQL删除命令?

[英]c# - SQL delete command?

When I delete a record, it works. 当我删除记录时,它可以工作。 But when I close the program and open it again, actually the record is not deleted. 但是,当我关闭程序并再次打开它时,实际上并没有删除记录。

private void button5_Click(object sender, EventArgs e) 
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Upper_Stage_Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        con.Open();
        MessageBox.Show("Delete Current Row of Database Open");

        if (MaxRows != 0)
        {
            SqlCommand Command = new SqlCommand("DELETE FROM Table1 WHERE Data_no='@inc'", con);

            try
            {
                Command.ExecuteNonQuery();
                MessageBox.Show("Record Deleted");
            }
            catch (SqlException)
            {
                MessageBox.Show("ERROR: Could not delete record");
            }
            MaxRows--;
            if (inc != 0)
            {
                inc--;
                NavigationRecords();
            }
            else
            {
                if (MaxRows != 1)
                {
                    inc++;
                    NavigationRecords();
                }
                else
                {
                    MessageBox.Show("No Record");
                }
            }
        }
        else
        {
            MessageBox.Show("No Record");
        }

        con.Close();
        MessageBox.Show("Delete Current Row of Database Closed");
        con.Dispose();
}

When I searched, some records can not be deleted because they are "master" record. 当我搜索时,某些记录无法删除,因为它们是“主”记录。 How can I delete the record TRULY? 如何删除TRULY记录?

you don't need quotes around '@inc': 您不需要在'@inc'周围加上引号:

SqlCommand Command = new SqlCommand("DELETE FROM Table1 WHERE Data_no=@inc", con);

Also you needs to provide the value for the @inc parameter too. 另外,您还需要提供@inc参数的值。

Command.Parameters.AddWithValue("@inc", inc); //inc is a variable that contain a value for the @inc parameter

Although specify the type directly and use the Value property is more better than AddWithValue . 尽管直接指定类型并使用Value属性比AddWithValue更好。 Check this for more details: Can we stop using AddWithValue() already? 请检查以下详细信息: Can we stop using AddWithValue() already?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM