【问题标题】:Select doesn't work from windows form application选择在 Windows 窗体应用程序中不起作用
【发布时间】: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


【解决方案1】:

更好的方法是:

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;
}

这应该可以正常工作。如果您只想检查文件是否存在于数据库中,top 1 也是为了提高性能。

【讨论】:

  • @alex 不要检查返回值,检查查询结果!查询不会影响任何记录
【解决方案2】:

由于您只想检查记录是否存在,因此您不需要从查询中返回任何字段。你可以这样写,使用ExecuteScalar:

var command = new SqlCeCommand("select 1 as Result from Files where nameFile = @file",con);
command.Parameters.AddWithValue("@file", name);
var result=command.ExecuteScalar();

这将只返回一个值而不是整个记录

只需确保 name 变量不包含任何不需要的空格,就像您的原始示例一样。

【讨论】:

  • OP 还需要更改对返回值的检查:)
【解决方案3】:

请始终使用parameterized SQL。这种字符串连接对SQL Injection 攻击开放。

var command = new SqlCeCommand("Select * From Files Where nameFile= @nameFile",con);
command.Parameters.AddWithValue("@nameFile", name);

int returnValue = command.ExecuteNonQuery();

【讨论】:

    【解决方案4】:

    看起来你的名字后面有一个空格 - 换句话说,说 name = "John",但在查询中它将是 'John'。这可能就是它不起作用的原因。

    此外,您应该使用参数化查询来避免 SQL 注入攻击。这样的事情应该可以解决您的问题:

    var command = new SqlCeCommand("Select * From Files
                                         Where nameFile=@Name",con);
    
    command.Parameters.AddWithValue("@Name", name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      相关资源
      最近更新 更多