从SQL Server表中删除一行

8

我想在SQL Server数据库表中使用按钮事件删除整行数据,但目前我的尝试都失败了。以下是我的操作:

public static void deleteRow(string table, string columnName, string IDNumber)
{
    try
    {
    using (SqlConnection con = new SqlConnection(Global.connectionString))
    {
         con.Open();
         using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + IDNumber, con))
         {
               command.ExecuteNonQuery();
         }
         con.Close();
    }
    }
    catch (SystemException ex)
       {
       MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
       }
    }
}

我一直收到这个错误信息:

在System.Data.dll中发生了第一个机会类型为“System.Data.SqlClient.SqlException”的异常 发生错误:操作数类型不匹配:文本与整数不兼容

表中的所有列都是TEXT类型。为什么不能将函数参数(类型为string)与列进行比较以找到匹配项?(然后删除该行?)

3
你应该使用参数来完成这个任务。 - James Hay
我不确定如何使用参数,有什么例子或资源吗? - ikathegreat
3
另外,附带说明一下:首先,你不应再使用TEXT - 自从SQL Server 2005之后,它已被弃用。改用VARCHAR(MAX)。还有:所有列都使用VARCHAR(MAX)看起来像是一个糟糕的设计 - 你真的需要每个列都有2 GB的文本吗?真的吗!?!设计和性能提示:使用适当的数据类型。 - marc_s
8个回答

20

由于您已经说明所有列名都是TEXT类型,因此需要使用单引号将IDNumber作为文本使用.....

    public static void deleteRow(string table, string columnName, string IDNumber)
    {
    try
    {
    using (SqlConnection con = new SqlConnection(Global.connectionString))
    {
         con.Open();
         using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
         {
               command.ExecuteNonQuery();
         }
         con.Close();
    }
    }
    catch (SystemException ex)
       {
       MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
       }
    }
 }

1
你应该始终使用参数化查询来执行此类操作。 - Halden Collier

6
要么将IDNumber改为int而不是string,要么如果它真的是string,则加上引号。

更好的方法是使用参数。


使用普通引号(“)时,我收到了以下错误信息:“发生错误:无效的列名'50012'。”其中50012是IDNumber(字符串)。 - ikathegreat
@ikathegreat - 尝试一下kashif的例子。使用参数可以避免像这样搞乱数据类型的麻烦。另外,正如其他帖子所说,你几乎肯定不想让所有这些字段都是TEXT。 - Jon B

5

使用参数尝试

.....................
.....................

    using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
             {
                   command.Paramter.Add("@IDNumber",IDNumber)
                   command.ExecuteNonQuery();
             }

.....................
.....................

使用语句时无需关闭连接


1

看起来IDNumber是一个字符串。它需要用单引号括起来。

"DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber + "'"

这里返回:发生错误:数据类型text和varchar在等于运算符中不兼容。 - ikathegreat

1

您可以将"columnName"类型从TEXT更改为VARCHAR(MAX)。不能使用"="操作符来操作TEXT列。
请参阅此主题


0
private void button4_Click(object sender, EventArgs e)
{
    String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;

    SqlCommand sqlcom = new SqlCommand(st, myConnection);
    try
    {
        sqlcom.ExecuteNonQuery();
        MessageBox.Show("delete successful");
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}



private void button6_Click(object sender, EventArgs e)
{
    String st = "SELECT * FROM suppliers";

    SqlCommand sqlcom = new SqlCommand(st, myConnection);
    try
    {
        sqlcom.ExecuteNonQuery();
        SqlDataReader reader = sqlcom.ExecuteReader();
        DataTable datatable = new DataTable();
        datatable.Load(reader);
        dataGridView1.DataSource = datatable;
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

0
如果您正在使用MySql Wamp,这段代码可以正常工作。
string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();

MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}

0
private void DeleteProductButton_Click(object sender, EventArgs e)
{


    string ProductID = deleteProductButton.Text;
    if (string.IsNullOrEmpty(ProductID))
    {
        MessageBox.Show("Please enter valid ProductID");
        deleteProductButton.Focus();
    }
    try
    {
        string SelectDelete = "Delete from Products where ProductID=" + deleteProductButton.Text;
        SqlCommand command = new SqlCommand(SelectDelete, Conn);
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 15;

        DialogResult comfirmDelete = MessageBox.Show("Are you sure you want to delete this record?");
        if (comfirmDelete == DialogResult.No)
        {
            return;
        }
    }
    catch (Exception Ex)
    {
        MessageBox.Show(Ex.Message);

    }
}

你的回答相比于这个已有7年历史的问题的被采纳的答案有何改进之处? - skolldev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接