繁体   English   中英

将字符串返回到有关搜索的SQL Server查询

[英]Return a string to a SQL server query about searching

我试图找出正在上传的文件是否已存在于服务器中。 我这样做的一种方法是检查是否存在相同的文件名。 但是,在代码中,somethig似乎不正确。 我使用SSMS运行查询并且它可以工作,但是当我将它放入Visual Studio时,我的返回类型是SQL.Data.Command而不是实际的字符串本身。 有人可以指点我正确的方向吗?

if (coda_file_upload.HasFile)
{
    coda = Path.GetFileName(filePath);  //gets the file name
    using (connection = new SqlConnection(connection_string))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = "SELECT * FROM name_table WHERE file_name LIKE '%"+coda+"%' ";

        cmd.Connection = connection;
        connection.Open();
        cmd.ExecuteNonQuery();
        connection.Close();

        string sample = Convert.ToString(cmd);

        if (cmd.ToString().Equals(String.Empty))
        {
            coda_file_upload.SaveAs(Server.MapPath("~/") + coda);
            input_data = System.IO.File.ReadAllText(Server.MapPath("~/") + coda);
            parse_CODA(input_data, coda);

            testing.Text = "Success";
        }

        else
            testing.Text = "File exists, please try another file.";

    }

我的'else'每次都被执行而不是if。 为了仔细检查,我打印出查询'string sample',当我看到返回的值是SQL.Data.Command时

您的代码中存在两个大问题:

  1. 不要连接字符串以生成sql命令文本。
  2. 在select查询上使用ExecuteNonQuery是错误的。 您需要ExecuteReader或ExecuteScalar

我们来看看如何修复代码

string input_data = string.Empty;
using (connection = new SqlConnection(connection_string))
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;

    cmd.CommandText = "SELECT * FROM name_table WHERE file_name LIKE @name";
    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = "%" + filename + "%";
    cmd.Connection = connection;
    connection.Open();

    // Try to execute the command and read back the results.
    SqlDataReader reader = cmd.ExecuteReader();

    // If there is no record or the field to check for emptyness is empty
    if(!reader.Read() || string.IsNullOrEmpty(reader.GetString("SampleField"))
         input_data = AcceptFile(coda);
    else
         testing.Text = "File exists, please try another file.";
 }

 private string AcceptFile(string coda)
 {
      coda_file_upload.SaveAs(Server.MapPath("~/") + coda);
      string readText = System.IO.File.ReadAllText(Server.MapPath("~/") + coda);
      parse_CODA(readText, coda);
      testing.Text = "Success";
      return readText;
 }

如果您只是想知道是否存在与fieldname匹配的行,那么您不需要检索任何记录,但您可以使用与T-SQL运算符EXISTS结合的ExecuteScalar从单行获取单个值

cmd.CommandText = @"IF EXISTS(SELECT 1 FROM name_table 
                              WHERE file_name LIKE @name) 
                              SELECT 1 ELSE SELECT 0";
cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = "%" + filename + "%";
int result = Convert.ToInt32(cmd.ExecuteScalar());
if(result == 0)
    .... no record found....
else
    .... record exists...

作为声明错误的一部分,您的问题是由于您无法使用对SqlCommand的引用并应用ToString希望获得有意义的东西。 该类不能使用ToString执行命令并返回返回数据集中存在的任何字段。 该类只返回其自身的完整限定名称。

第一 :当你想要检查时不要使用Select * ,而是使用select 1

第二 :你说: -

我的返回类型是SQL.Data.Command而不是实际的字符串本身

下一行是原因: -

string sample = Convert.ToString(cmd);

固定代码: -

if (coda_file_upload.HasFile)
    {
        coda = Path.GetFileName(filePath);  //gets the file name
        using (connection = new SqlConnection(connection_string))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "SELECT 1 FROM name_table WHERE file_name LIKE '%"+coda+"%' ";

            cmd.Connection = connection;
            connection.Open();
            string result = Convert.ToString(cmd.ExecuteScalar());
            connection.Close();

            if (result != "1")
            {
                coda_file_upload.SaveAs(Server.MapPath("~/") + coda);
                input_data = System.IO.File.ReadAllText(Server.MapPath("~/") + coda);
                parse_CODA(input_data, coda);

                testing.Text = "Success";
            }

            else /* Result == 1 */
                testing.Text = "File exists, please try another file.";

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM