从SQL Server表中删除一行 [英] Delete a row from a SQL Server table
问题描述
我正尝试使用按钮事件从SQL Server数据库表中删除整行。到目前为止,我的尝试都没有成功。这就是我想要做的:
I'm trying to simply delete a full row from my SQL Server database table using a button event. So far none of my attempts have succeeded. This is what I'm trying to do:
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'的第一次机会异常发生:操作数类型冲突:文本与int不兼容
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll An error occurred: Operand type clash: text is incompatible with int
表中的所有列均为 TEXT
类型。为什么我不能将类型 string
的函数自变量与列进行比较以找到匹配项? (然后删除该行吗?)
All of the columns in the table are of TEXT
type. Why cannot I compare the function argument of type string
to the columns to find the match? (And then delete the row?)
推荐答案
正如您所说的,所有列名都是TEXT类型,因此,有需要通过在IDNumber周围使用单引号来将IDNumber用作文本。..
As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around 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));
}
}
}
这篇关于从SQL Server表中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!