【发布时间】:2013-07-02 02:46:14
【问题描述】:
我想检查一个文件的数据是否存在于表中
public bool ExistFile(string name)
{
bool result = false;
SqlCeConnection con = new SqlCeConnection();
con.ConnectionString =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
con.Open();
var command = new SqlCeCommand("Select * From Files
Where nameFile='"+ name +" ' ",con);
int returnValue = command.ExecuteNonQuery();
command.Dispose();
con.Close();
if (returnValue > 0)
result = true;
else
result = false;
return result;
}
在变量“name”中,我正在发送表中的现有字符串,但“returnValue”始终为 -1。 在 testQuery 面板中它有效,我正在复制相同的查询并且它有效,返回值为一行。 问题出在哪里,我该如何解决?
【问题讨论】:
-
你确定 name + " 后面的那个空格吗?
-
Where nameFile='"+ name +" ' ".. 在这里修复你的空间..
-
你的名字后面多了一个空格。
nameFile='"+ name +" '应该是nameFile='"+ name +"'。但是,您应该使用参数化查询来避免 SQL 注入攻击。 -
您使用了错误的方法:
SqlCeCommand.ExecuteNonQuery:“对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数。对于所有其他 DML 语句,返回值为-1。” -
另外,当你关心的只是行是否存在时,不要
SELECT *(甚至SELECT COUNT(*)) - 使用EXISTS谓词。
标签: c# winforms select sql-server-ce