Java:使用数组作为向mysql插入数据的参数和条件

Java:使用数组作为向mysql插入数据的参数和条件,java,mysql,arrays,logging,Java,Mysql,Arrays,Logging,所以,我对如何插入数组作为参数条件有点困惑。 我想添加数组作为我的参数。在这个程序中,我读取日志数据并将日志级别设置为参数条件,因此当它读取下一个日志级别时,它将停止并将数据插入数据库。因此,我有点困惑,到底是如何做到这一点的 此日志文件如下所示 调试[CorporateUserSMImpl]30-05-2019 00:01:04:id=2c9dc30c673209d201675e3e5c961456 警告[登录操作]30-05-2019 00:01:04:go主页batchID=2C9DC30

所以,我对如何插入数组作为参数条件有点困惑。 我想添加数组作为我的参数。在这个程序中,我读取日志数据并将日志级别设置为参数条件,因此当它读取下一个日志级别时,它将停止并将数据插入数据库。因此,我有点困惑,到底是如何做到这一点的

此日志文件如下所示 调试[CorporateUserSMImpl]30-05-2019 00:01:04:id=2c9dc30c673209d201675e3e5c961456 警告[登录操作]30-05-2019 00:01:04:go主页batchID=2C9DC30C6AC6B815016B0452C3D41EF时间ENDCALLBO=2019-05-30 00:01:04.198的登录过程

因此,当它读取下一个日志级别时,它将停止并保存上一行

新的!!! 如果日志文件如下所示,该怎么办 调试[AccountDAOImpl]30-05-2019 00:01:45:

开始调用方法GetByAccountGroupId和AccountTypeNew 12
调试[AccountDAOImpl]30-05-2019 00:01:45:currentPage=1

您可以插入数组作为参数条件,通过替换sql将数据插入MySQL,如下所述:

字符串[]levParam={DEBUG,WARN,INFO,ERROR}; List listparam=Arrays.asListlevParam

package com.example.dev1.controller;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/*import java.sql.ResultSet;*/
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import javax.swing.JApplet;

public class ReadLg extends JApplet {

    private static final long serialVersionUID = 1L;

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String[] lev_param = { "DEBUG", "WARN", "INFO", "ERROR" };
        List<String> listparam = Arrays.asList(lev_param);
        String temp = null;
        PreparedStatement ps = null;
        Connection con = null;
        /* ResultSet rs = null; */

        try {
            BufferedReader br = new BufferedReader(new FileReader("All.log"));
            String username = ****;
            String pwd = ****;
            String connurl = "jdbc:mysql://10.247.36.174:3306/d_accesslog?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

            con = DriverManager.getConnection(connurl, username, pwd);

            String line = null;
            while ((line = br.readLine()) != null) {
                temp+=line;
                if (line.equals(listparam)) {
                    String sql = "INSERT INTO t_weblogic_test (RawData) values ('\''+line+'\'')";
                    temp=null;
                } 

                ps = con.prepareStatement(sql);
                ps.executeUpdate();
            }

            br.close();
            con.close();
            ps.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这里有一些东西需要优化。您的具体问题是将整行代码与无法工作的ArrayList进行比较:line.equalListParam。您应该获取行的第一个标记,并查看列表是否包含这样的值。一种可能的方法是:

while ((line = br.readLine()) != null) {
     String line=null;

            String firstWord= line.split(" \\[")[0];
            if(listparam.contains(firstWord)) { 

      processMessages(line, br, listparam, ps);

    }
}


   private static void processMessages(String line, BufferedReader br, List<String> listparam, PreparedStatement ps) throws IOException, SQLException {
String message = line;

// Scan until the end of the message, eg the start of the next message
while ((line = br.readLine()) != null) {

 String lastWord= s.split(" \\[")[1];

    // Insert your message
     String sql = "INSERT INTO t_weblogic_test (RawData) values ('\''+lastWord+'\'')";
       ps = con.prepareStatement(sql);
       ps.executeUpdate();
    message = line; // Start of the new message

}
接下来,我建议使用try-with-resources构造来创建您的con、ps和br资源。如果出现任何问题,这将自动关闭它们。此外,我将使用一个prepared参数创建PreparedStatement,以最终传递日志消息,而不是将其连接到sql字符串中。这将提高性能,因为您只需要创建一次语句,而且更安全

我已经在下面稍微重写了您的代码,这是未经测试的,因此可能仍然包含一些缺陷,但我希望您了解总体思路:

String firstWord = line.split(" ",2)[0];
if(listparam.contains(firstWord)) {

}

要获得更高的性能,请使用字符串生成器

谢谢,但这不是我的意思。我的意思是如何将数组作为参数。My array param是我的日志级别,其中包含{DEBUG,WARN,INFO,ERROR}。因此,当我读取日志文件时,它将读取每一行,并在读取日志级别时停止,并保存上一行谢谢您的回复。我对SQL的工作原理有点困惑。将值更改为。那么它将在哪个会话中将字符串中的值插入db?sql中使用的问号是参数占位符。ps.setString,消息将确保驱动程序将参数替换为消息字符串。“1”表示要替换第一个参数。这样,您就可以在一个sql字符串中使用多个参数,并使用ps.setString、ps.setInt、。。。方法设置这些参数的值。该系统确保语句只需编译一次,因为只有参数值会更改,而不是整个sql字符串。它还可以防止sql注入,因为驱动程序会处理参数的替换。我希望这能让它变得更清楚,但也可以查看其他信息。谢谢。。如果你不介意的话,我想问最后一个问题。。如何读取这一行?这将根据分隔符分割该行,因此在每个空格之后,并将结果存储在数组中。“2”表示结果数组的大小,因为在本例中我们只需要第一个字,所以2就足够了。结果数组的索引0将包含我们的第一个单词,数组的索引1将包含该行的其余部分。如果省略限制参数“2”,则生成的数组将包含每个单独单词的条目。
public static void main(String[] args) {
    String connurl = "jdbc:mysql://10.247.36.174:3306/d_accesslog?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    String username = "****";
    String pwd = "****";
    // Use a prepared parameter in the sql string
    String sql = "INSERT INTO t_weblogic_test (RawData) values (?)";

    String[] levParam = { "DEBUG", "WARN", "INFO", "ERROR" };
    List<String> listparam = Arrays.asList(levParam);

    // Use a try-with-resources block to automatically handle the closing of the resources
    try(Connection con = DriverManager.getConnection(connurl, username, pwd); 
        PreparedStatement ps = con.prepareStatement(sql);
        BufferedReader br = new BufferedReader(new FileReader("All.log"));) {

      String line = null;
      while ((line = br.readLine()) != null) {
        // Get first token
        String firstWord = line.split(" ",2)[0];
        if(listparam.contains(firstWord)) { // Start of the first log message
          // Process all the messages from the log file
          processMessages(line, br, listparam, ps);
          break;
        }
      }
    } catch(SQLException ex) {
      // ex handling
    } catch(IOException ex) {
      // ex handling
    }
  }

  private static void processMessages(String line, BufferedReader br, List<String> listparam, PreparedStatement ps) throws IOException, SQLException {
    String message = line;

    // Scan until the end of the message, eg the start of the next message
    while ((line = br.readLine()) != null) {
      // Get first token
      String firstWord = line.split(" ",2)[0];
      if(listparam.contains(firstWord)) { // Start of the next log message
        // Insert your message
        ps.setString(1, message);
        ps.executeUpdate();
        message = line; // Start of the new message
      } else { // Continuation of the current message
        message = message.concat(line);
      }
    }

    if(!message.isEmpty()) {
      // Insert the last message from the log file
      ps.setString(1, message);
      ps.executeUpdate();
    }
  }
package com.example.dev1.controller;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.List;

public class ReadLg3 {
    public static void main(String[] args) {
        String conn = "jdbc:mysql://ipaddress/d_accesslog?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        String username = "****";
        String pwd = "****";
        String sql = "INSERT INTO t_weblogic_test (RawData) values (?)";

        String[] levParam = { "<DEBUG>", "<WARN", "<INFO", "<ERROR>","INFO", "WARN","DEBUG","ERROR" };
        List<String> listparam = Arrays.asList(levParam);

        try (Connection con = DriverManager.getConnection(conn, username, pwd);
                PreparedStatement ps = con.prepareStatement(sql);
                BufferedReader br = new BufferedReader(new FileReader("All.log"));) {

            String line = null;
            while ((line = br.readLine()) != null) {
                String firstWord = line.split(" ", 2)[0];
                if (listparam.contains(firstWord)) {
                    processMessages(line, br, listparam, ps);
                    break;
                } else {
                    System.err.println("Failed!!");
                }
            }
        } catch (Exception ex) {
            System.err.println("Error in \n" + ex);
        }
    }

    public static void processMessages(String line, BufferedReader br, List<String> listparam, PreparedStatement ps)
            throws Exception {
        StringBuilder message = new StringBuilder();
        message.append(line);
        while ((line = br.readLine()) != null) {
            String firstWord = line.split(" ", 2)[0];
            if (listparam.contains(firstWord)) {
                ps.setString(1, message.toString());
                ps.executeUpdate();
                message.setLength(0);
                message.append(line);
            } else {
                message.append("\n" + line);
            }
        }

        if (message.length() > 0) {
            ps.setString(1, message.toString());
            ps.executeUpdate();
        }
    }
}