Write arraylist to a database java

前端 未结 5 1701
有刺的猬
有刺的猬 2020-12-21 06:22

I have two arraylists to insert into 2 columns in a database table as follows:

arraylist1: 123444, 324555, 6423643, 532326
arraylist2: jkfdsl, nkjfsdlj, jdsl         


        
5条回答
  •  没有蜡笔的小新
    2020-12-21 06:48

    Here's something that you can do:

    Assuming that you're trying to create one row, where the 1st column will contain the content of the first ArrayList in comma-separated format and the 2nd column will contain the content of the secondArrayList

    StringBuilder buffer = new StringBuilder();
    boolean processedFirst = false;
    String firstParam = null, secondParam = null;
    
    try{
        for(String record: arrayList1){
            if(processedFirst)
                buffer.append(",");
            buffer.append(record);
            processedFirst = true;
        }
        firstParam = buffer.toString();
    }finally{
        buffer = null;
    }
    processedFirst = false;
    buffer = new StringBuilder();
    try{
        for(String record: arrayList2){
            if(processedFirst)
                buffer.append(",");
            buffer.append(record);
            processedFirst = true;
        }
        secondParam = buffer.toString();
    }finally{
        buffer = null;
    }
    secondParam = buffer.toString();
    
    String sql = "INSERT INTO soundsdata.splog (arraylist1, arraylist2) VALUES(?,?)";
    try{
        psmt = (PreparedStatement) con.prepareStatement(sql);
        pstmt.setString(1,firstParam);
        pstmt.setString(2,secondParam);
        pstmt.executeUpdate();
    }finally {
        pstmt.close();
    }
    

提交回复
热议问题