簡體   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