ika*_*eat 6 c# sql-server delete-row
我试图使用按钮事件从我的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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我一直收到错误:
System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的第一次机会异常发生错误:操作数类型冲突:文本与int不兼容
表中的所有列都是TEXT
类型.为什么我不能将类型的函数参数string
与列进行比较以找到匹配?(然后删除该行?)
小智 17
正如你所说的所有列名都是TEXT类型的,所以,需要使用IDNumber作为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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用参数
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
{
command.Paramter.Add("@IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
Run Code Online (Sandbox Code Playgroud)
使用语句中无需关闭连接
归档时间: |
|
查看次数: |
111139 次 |
最近记录: |