程序在 IF/else SQL 语句期间挂起

本文关键字:语句 挂起 SQL else IF 程序 | 更新日期: 2023-09-27 18:30:59

我正在创建一个注册应用程序,该应用程序有两种工作方式:在线和离线。我们使用条形码将自己扫描到应用程序中。当您扫描在线条形码时,它会给您 6 个数字和一个"L",例如 242565L ,程序将选取它并在 SQL 数据库中搜索相应的 ID 号。离线条形码包含带有"的名称文本值,例如史密斯,约翰

当我运行它并扫描在线条形码时,它工作正常。但是当我断开与互联网的连接以便它找不到数据库并扫描我的代码时,它会拾取 1 个字母并冻结并挂起,直到我停止该过程。

请问有什么想法吗?C# 新手

这是主要代码:

            {
            SqlConnection DBConnection = new SqlConnection("DataSource=DATABASE;Initial Catalog=imis;Integrated Security=True");
            SqlCommand cmd = new SqlCommand();
            Object returnValue;
            string txtend = textBox1.Text;
            try
            {
                DBConnection.Open();
            }
            catch
            {
                DBConnection.Close();
            }
            if (DBConnection.State == ConnectionState.Open)
            {
                if (textBox1.Text.Length != 7) return;
                cmd.CommandText = "SELECT last_name +', '+ first_name +''t ('+major_key+')'t' from name where id ='" + textBox1.Text.Replace(@"L", "") + "'";
                // MessageBox.Show(textBox1.Text.Replace(@"L", ""));
                cmd.CommandType = CommandType.Text;
                cmd.Connection = DBConnection;
                // sqlConnection1.Open();
                returnValue = cmd.ExecuteScalar() + "'t (" + textBox1.Text.Replace(@"L", "") + ")";
                DBConnection.Close();

                if (listBox1.Items.Contains(returnValue))
                {
                    for (int n = listBox1.Items.Count - 1; n >= 0; --n)
                    {
                        string removelistitem = returnValue.ToString();
                        if (listBox1.Items[n].ToString().Contains(removelistitem))
                        {
                            // listBox1.Items.RemoveAt(n);
                        }
                    }
                }
                else
                    listBox1.Items.Add(returnValue);
                textBox1.Text = null;
                if (listBox1.Items.Count != 0) { DisableCloseButton(); }
                else
                {
                    EnableCloseButton();
                }
                label6.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
            }
            else
            {
                try
                {
                    string lastTwoChars = txtend.Substring(txtend.Length - 1);
                    returnValue = textBox1.Text.Replace(@"*", "");
                    if (lastTwoChars != "*") return;
                    {
                        if (listBox1.Items.Contains(returnValue))
                        {
                            for (int n = listBox1.Items.Count - 1; n >= 0; --n)
                            {
                                string removelistitem = returnValue.ToString();
                                if (listBox1.Items[n].ToString().Contains(removelistitem))
                                {
                                    //listBox1.Items.RemoveAt(n);
                                }
                            }
                        }
                        else
                            listBox1.Items.Add(returnValue);
                        textBox1.Text = null;
                        if (listBox1.Items.Count != 0) { DisableCloseButton(); }
                        else
                        {
                            EnableCloseButton();
                        }
                        label6.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
                    }
                }
                catch
                {
                }
            }
    }

程序在 IF/else SQL 语句期间挂起

尝试调试它。 挂起程序时暂停程序,并查看挂起的位置。 如果它挂在 SQL 查询上,您可能希望对它设置超时。

也不应该像这样创建查询

cmd.CommandText = "SELECT last_name +', '+ first_name +''t ('+major_key+')'t' from name where id ='" + textBox1.Text.Replace(@"L", "") + "'";

它对SQL注入开放。

使用参数化 SQL 或其他形式的保护:

SqlCommand command = new SqlCommand("SELECT last_name +', '+ first_name +''t ('+major_key+')'t' from name where id =@Name"
command.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", ""))); 

编辑

如果要在连接上设置超时,可以在此处查看MSDN:可以在连接字符串中设置超时参数,也可以简单地设置

DBConnection.ConnectionTimeout = yourTime;

这将使连接在等待超时参数后失败。

而不是使用try..catch 要确定您是否具有活动的数据库连接,请改用"using"块。

它更有效,并且在不再需要时会自动关闭/销毁数据库连接。

通过这种方式,您可以在 using 语句中移动 try catch 块并捕获与代码相关的错误,而不必担心是否有打开的数据库连接或互联网连接的状态。

在这个例子中,我从我自己的代码库中获取了代码,并且我使用的是oracle数据库连接。 您需要将单词"Oracle"替换为"SQL"请注意,db 之间的参数声明略有不同。Oracle 使用 ":",MsSql 使用 '@' 来指定参数。

例如。

  DataSet myDataSet= new DataSet();
  using (OracleConnection conn = new OracleConnection(connectionString))
   {
     using (OracleCommand cmd = new OracleCommand())
       {
        cmd.BindByName = true;
        #region SQL Core
           StringBuilder sql = new StringBuilder();
           sql.Append(" <Your SQL Here> ");
        #endregion
        #region - ADD SQLParameter
          // use Parameters to avoid SQL Injection like @param1
          sql.Append(" AND (columnname = @param1 ");
          OracleParameter param1 = new OracleParameter("@param1", OracleDbType.Varchar2); 
          param1.Value = yourValue;
          cmd.Parameters.Add(param1);
        #endregion
        cmd.CommandText = sql.ToString();
        cmd.Connection = conn;
        try
          {
             conn.Open();
             try
             {
               OracleDataAdapter adapter = new OracleDataAdapter(cmd);
               adapter.Fill(myDataSet, "myDataSetName");
             }
             catch (Exception myex)
             {
               //Handle General Exception
                Console.Write(myex);
             }
          }
          Catch (OracleException myex)
          {
            //Handle Oracle Exception
              Console.Write(myex);
          }
       }//end of inner 'using'
    }//end of outer 'using'
//Now you have a populated Data Set, you can loop over it extracting values.
//This acts like an offline record set
//Or you can Bind MyDataSet to a GridView to see the data in your offline table.
   //Output Result set in expected XML format and return
   DataTable dataTable = myDataSet.Tables[0];
   if (dataTable.Rows.Count > 0)
     {
     for (int i = 0; i < dataTable.Rows.Count; i++)
      {
       DataRow dataRow = dataTable.Rows[i];
       for (int x = 0; x < dataTable.Columns.Count; x++)
       {
       //dataTable.Rows[i].Table.Columns[x].ColumnName.ToString()
       if (dataTable.Rows[i].Table.Columns[x].ColumnName == "YourColumnName") 
       { 
         //Get value with dataRow[x]
       }
      }//end 2nd for
     }//end 1st for
    }//end outer if.
抱歉,如果

有任何语法错误,这一切都是在没有智能的情况下编辑的。它只是给你要点。就这样。

通过使用脱机数据集,您将获得更少的应用程序挂起。