C# 从windows窗体应用程序中选择不起作用
我想检查表中是否存在关于文件的数据C# 从windows窗体应用程序中选择不起作用,c#,winforms,select,sql-server-ce,C#,Winforms,Select,Sql Server Ce,我想检查表中是否存在关于文件的数据 public bool ExistFile(string name) { bool result = false; SqlCeConnection con = new SqlCeConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; con.Ope
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;
}
在变量名中,我发送表中现有的字符串,但returnValue始终为-1。
在testQuery面板中,它工作,我复制相同的查询,它工作,返回值是一行。
问题出在哪里?我如何解决这个问题?更好的方法是:
var command = new SqlCeCommand("select top 1 * from Files where nameFile = @file",con);
command.Parameters.AddWithValue("@file", name);
var returned = command.ExecuteScalar();
if (returned != null)
{
returned = true;
}
这应该很好。另外,如果您只想检查数据库中是否存在文件,则排名前1的是性能。看起来名称后面有一个空格,换句话说,就是name=John,但在查询中它将是“John”。这可能就是它不起作用的原因 此外,应该使用参数化查询来避免SQL注入攻击。类似这样的东西可以解决您的问题:
var command = new SqlCeCommand("Select * From Files
Where nameFile=@Name",con);
command.Parameters.AddWithValue("@Name", name);
请经常使用。这种类型的字符串连接对攻击是开放的
因为您只想检查记录是否存在,所以不需要从查询中返回任何字段。您可以这样编写,使用: 这将只返回一个值,而不是整个记录
只需确保name变量不包含与原始示例相同的任何不需要的空格。是否确定name+后面的空格?其中nameFile='+name+'。。。。在这里固定空格..你在名字后面有一个额外的空格。nameFile='+name+'应该是nameFile='+name+'。但是,您应该使用参数化查询来避免SQL注入攻击。您使用了错误的方法::对于UPDATE、INSERT和DELETE语句,返回值是受命令影响的行数。对于所有其他DML语句,返回值为-1。此外,如果您只关心行是否存在,请不要选择*或甚至选择COUNT*——使用EXISTS谓词。@alex不检查返回值,请检查查询结果!任何记录都不会受到查询的影响。查询还需要更改对返回值的检查:
var command = new SqlCeCommand("Select * From Files Where nameFile= @nameFile",con);
command.Parameters.AddWithValue("@nameFile", name);
int returnValue = command.ExecuteNonQuery();
var command = new SqlCeCommand("select 1 as Result from Files where nameFile = @file",con);
command.Parameters.AddWithValue("@file", name);
var result=command.ExecuteScalar();