将arraylist写入数据库java [英] Write arraylist to a database java

查看:37
本文介绍了将arraylist写入数据库java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组列表要插入到数据库表的 2 列中,如下所示:

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

arraylist1: 123444, 324555, 6423643, 532326
arraylist2: jkfdsl, nkjfsdlj, jdslkfjdlkj, jfsldjfsk, fjdlskjfs

我编写了以下代码来插入数组列表,但它不起作用.我将感谢您的帮助.

I wrote the following code to insert the arraylists but it is not working. I will appreciate your help.

try {
// Prepare a statement to insert a record

String sql = "INSERT INTO soundsdata.splog (arraylist1, arraylist2) VALUES(?,?)";
pstmt = (PreparedStatement) con.prepareStatement(sql);

pstmt.setArray(1,sptospring);
pstmt.setString(2,eachList.toString());

// Insert the row
pstmt.executeUpdate();
}finally {
pstmt.close();
}

推荐答案

您可以执行以下操作:

假设您正在尝试创建一行,其中第一个 column 将包含逗号分隔格式的第一个 ArrayList 的内容和第二个 column 将包含第二个ArrayList

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();
}

这篇关于将arraylist写入数据库java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆