【问题标题】:Make try catch statement identify various errors使 try catch 语句识别各种错误
【发布时间】:2018-11-28 13:40:42
【问题描述】:

您好,我正在使用 JAVA,制作一个可以从文本文件直接插入数据库的 swt 应用程序。我正在努力解决最后的部分,即应用程序的错误检测部分。我可以很好地插入数据库,它会在应该的地方给出一个错误。我想要做的是,如果有多个错误,它会指出有多个错误,而不仅仅是一个。现在我的代码仍然将文本文件的正确行插入到数据库中,并且没有插入错误的行,但它只标记了一个错误。有没有办法在 catch 子句周围放置一个 if 语句,或者有没有更有效的方法来识别多个错误?我想对所有 SQL 异常执行此操作,例如错误字段、错误值类型等。

        buttoninsert.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            System.out.println("create jdbc connection using properties file");

            Connection con = null;


            // use try becuase it tends to fail sometimes and we want error messages

            try {

                //load properties file we have created
                Properties prop = loadPropertiesFile();

                //declare vars and get the properties at the same time
                String driverClass = prop.getProperty("SQLSERVERJDBC.driver");
                String url = prop.getProperty("SQLSERVERJDBC.url");
                String username = prop.getProperty("SQLSERVERJDBC.username");
                String password = prop.getProperty("SQLSERVERJDBC.password");


                // have to instance driver
                Class.forName(driverClass).newInstance();

                // make connection object using the previous things as parameters
                con = DriverManager.getConnection(url, username, password);

                //this if is to verify the connection
                if (con != null) {
                    System.out.println("connection created successfully using properties file");


                }

                else {
                    System.out.println(" unable to create connection");

                }


                BufferedReader reader = new BufferedReader(new FileReader(
                        "C:\\Users\\darroyo\\Documents\\pruebasx.txt"));

                ArrayList<String> array1 = new ArrayList<String>();
                // Read line from file.
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {

                        break;
                    }
                    // Split line on space.
                    String[] parts = line.split("");
                    //part in parts
                    for (String part : parts) {

                        //part is the element in this case each fix tag with value
                        array1.add(part);

                    }
                    String query = " insert into FRONTMC.HECHO (folio_hecho, folio_orden, emisora, serie,"
                            + "clave_sentido, titulos_hecho, precio, importe, liquidacion, contraparte, id_estatus, isin, contrato,"
                            + "secondary_exec_id, exec_id, F11_ClOrdID, fecha_recepcion, fecha_sentra)"
                                + " values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,convert(varchar(30),cast(? as datetime),120),convert(varchar(30),cast(? as datetime),120))";

                              // create the mysql insert preparedstatement
                              PreparedStatement preparedStmt = con.prepareStatement(query);


                              for(int counter =0; counter< array1.size();counter++){
                                  if(array1.get(counter).substring(0, 3).equals("37=")){
                                      preparedStmt.setString (1, array1.get(counter).substring(3));

                                  }
                                  if(array1.get(counter).substring(0, 3).equals("37=")){
                                      preparedStmt.setString (2, array1.get(counter).substring(3));
                                  }

                                  // change emisora and serie to 48 with bd
                                  if(array1.get(counter).substring(0, 3).equals("49=")){
                                      preparedStmt.setString (3, array1.get(counter).substring(3));
                                  }

                                  if(array1.get(counter).substring(0, 4).equals("447=")){
                                      preparedStmt.setString (4, array1.get(counter).substring(4));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("54=")){
                                      preparedStmt.setString (5, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("32=")){
                                      preparedStmt.setString (6, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("31=")){
                                      preparedStmt.setString (7, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 4).equals("381=")){
                                      preparedStmt.setString (8, array1.get(counter).substring(4));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("63=")){
                                      preparedStmt.setString (9, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 4).equals("448=")){
                                      preparedStmt.setString (10, array1.get(counter).substring(4));
                                  }
                                  if(array1.get(counter).substring(0, 4).equals("150=")){
                                      preparedStmt.setString (11, array1.get(counter).substring(4));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("48=")){
                                      preparedStmt.setString (12, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 2).equals("1=")){
                                      preparedStmt.setString (13, array1.get(counter).substring(2));
                                  }
                                  if(array1.get(counter).substring(0, 4).equals("527=")){
                                      preparedStmt.setString (14, array1.get(counter).substring(4));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("17=")){
                                      preparedStmt.setString (15, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("11=")){
                                      preparedStmt.setString (16, array1.get(counter).substring(3));
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("52=")){

                                      String date = array1.get(counter).substring(3);

                                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                                        SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
                                        String ds2 = sdf2.format(sdf1.parse(date));
                                        String x = date.substring(9, 21);
                                        String newfecha1 = ds2+" "+x;


                                      preparedStmt.setString (17, newfecha1);
                                  }
                                  if(array1.get(counter).substring(0, 3).equals("52=")){

                                      String date = array1.get(counter).substring(3);

                                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                                        SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
                                        String ds2 = sdf2.format(sdf1.parse(date));
                                        String x = date.substring(9, 21);
                                        String newfecha1 = ds2+" "+x;


                                      preparedStmt.setString (18, newfecha1);
                                  }

                              }

                              // execute the preparedstatement


                              preparedStmt.execute();
                              displaymsjfix.setText("exitoso");    
                }

                System.out.println(array1);


                reader.close();

                //creating the statement(should check to use prepared statement in the future

                // fecha recp y fecha sentra in query and for and ? and order



                          //notifies you that it was completed
                System.out.println("insert complete");
                // loop to check the digits ex. for() array.1get(counter).substring(0,3).equals("23=")

                //error messages
            }catch (SQLException eb) {
                eb.printStackTrace();
            } 

            //ERROR MESSAGE FECHA just get line number
            catch (Exception eb) {

                System.out.println("Error in date ");
            } finally {

                try {
                    if (con != null) {
                        con.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }



        }
    });

【问题讨论】:

    标签: java sql exception try-catch


    【解决方案1】:

    您不会抛出多个错误,因为一个方法只能抛出一个异常,而 SQL 连接器只会在第一个异常处快速失败。我认为您所追求的是如何捕获各种错误并将这些错误显示给用户?

    您可以解析 SQLException 中返回的消息字符串,然后显示更详细的错误消息吗?

    【讨论】:

    • 哦,我明白了,谢谢这真的清除了它,我真的更想问是否可能。但是有多个错误,它是否仍然检测到它们并且在消息字符串中我可以识别各种错误吗?
    • 我可能是错的,但我很确定如果您尝试执行无效的 SQL 查询,驱动程序只会返回它发现的第一个错误。因此,如果您希望自己可能必须为 SQL 查询编写自己的解析器,然后自己处理多个错误消息,那么您不会从驱动程序类中得到一个以上的错误源。
    【解决方案2】:

    当您执行查询时,您只会在 SQLException 中获得最高优先级错误(它发现的第一个错误),这与您在数据库本身上将查询作为本机 SQL 执行时遇到的错误类似(所以不是通过Java 代码,但通过 SQLDeveloper 或类似的 SQL 工具)。

    在你的情况下,我能给你的最好的选择是:

    1. 执行查询前的手动验证
    2. 如果数据库值是数字、日期等,请不要只使用 .setString

    在您当前的代码中,您将所有值作为字符串插入到数据库中。通常您只想将.setString 用于TEXTVARCHAR 值。如果数据库值为NUMERIC,我建议使用.setInteger.setLong(或其他取决于NUMERIC 的大小)。如果所有 Java 字段都只是字符串,从您使用的许多 substrings 来看似乎是这种情况,您可以先在 Java 代码中将这些字符串转换为整数,然后在 PreparedStatement 上使用.setInteger

    它并没有真正回答你的问题,但至少你不会再得到不正确的值类型错误。

    如果您使用.setDate 而不是.setString,则查询的convert(varchar(30),cast(? as datetime),120) 部分可能只是?(我认为,不是100% 确定,因为我不确定您的输入数据是什么,以及 PreparedStatement 生成的查询是什么。您可能仍需要配置一些内容,以便在默认情况下不执行此操作时将其转换为正确的数据库日期格式。)

    【讨论】:

      【解决方案3】:

      如果您想要一个包含所有错误的列表,您需要在您的while-loop 中,而不是在外部try-catch

      1. 创建一个List&lt;String&gt; errors
      2. 解析异常消息并将其添加到列表中。
      3. 在程序运行结束时,打印出所有错误。

      【讨论】:

        【解决方案4】:

        从您的行“现在我的代码仍然将文本文件的正确行插入到数据库中,并且不会插入错误的行,但它只标记一个错误”,我假设您想继续触发 sqlqueries直到最后一行并收集出现的所有错误消息。

        你不应该那样做,这是一种不好的做法,但在 java 中我认为有办法。

        List<String> exceptionList = new ArrayList<String>();
        while(true)
        {
           //Your code
            try
             {
                //sql statements and prepared statements
             }
             catch(SqlException e)
             {
                    exceptionList.add(e.getMessage());
                    continue;
             }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-20
          • 2022-01-24
          • 2014-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多