简体   繁体   English

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

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

I am trying to find out if the file that is being uploaded already exists in the server. 我试图找出正在上传的文件是否已存在于服务器中。 And one way for me to do this is to check if the same file name exists. 我这样做的一种方法是检查是否存在相同的文件名。 However, somethig seems to not be correct in the code. 但是,在代码中,somethig似乎不正确。 I have run the query using SSMS and it works, but when I put it into Visual Studio, my return type is SQL.Data.Command and not the actual string itself. 我使用SSMS运行查询并且它可以工作,但是当我将它放入Visual Studio时,我的返回类型是SQL.Data.Command而不是实际的字符串本身。 Can someone please point me in the right direction? 有人可以指点我正确的方向吗?

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.";

    }

My 'else' gets executed every time instead of the if. 我的'else'每次都被执行而不是if。 To double check, I printed out the query to 'string sample' and thats when I see that the value being returned is SQL.Data.Command 为了仔细检查,我打印出查询'string sample',当我看到返回的值是SQL.Data.Command时

There are two big problems in your code: 您的代码中存在两个大问题:

  1. Do not concatenate strings to make sql command texts. 不要连接字符串以生成sql命令文本。
  2. Using ExecuteNonQuery on a select query is wrong. 在select查询上使用ExecuteNonQuery是错误的。 You need ExecuteReader or ExecuteScalar 您需要ExecuteReader或ExecuteScalar

Let's see how I fix the code 我们来看看如何修复代码

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

if you are just interested to know if a row matching the fieldname exists or not then you don't need to retrieve any record but you can just use an ExecuteScalar coupled with the T-SQL operator EXISTS to get a single value from a single row 如果您只是想知道是否存在与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...

A part from the stated errors, your problem is caused by the fact that you cannot use a reference to an SqlCommand and apply a ToString hoping to get out something meaningful. 作为声明错误的一部分,您的问题是由于您无法使用对SqlCommand的引用并应用ToString希望获得有意义的东西。 The class cannot use the ToString to execute the command and return whatever field is present in the returned data set. 该类不能使用ToString执行命令并返回返回数据集中存在的任何字段。 The class simply return the full qualified name of itself. 该类只返回其自身的完整限定名称。

First : Don't use Select * while you wanna just check, use select 1 instead. 第一 :当你想要检查时不要使用Select * ,而是使用select 1

second : You said:- 第二 :你说: -

my return type is SQL.Data.Command and not the actual string itself 我的返回类型是SQL.Data.Command而不是实际的字符串本身

the next line is the reason:- 下一行是原因: -

string sample = Convert.ToString(cmd);

Fixed code:- 固定代码: -

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