拆分对象

时间:2016-11-08 11:44:21

标签: java arraylist

我实现了一个接口setObject,它接受​​String,int,double等数据类型,我将在Insert语句中使用它。但是在我的数据库中插入数据时,它会给我一个值[a,b,c] [a,b,c] [a,b,c]。如何避免此输出?

接口:

public interface CallableStatement
{
    ArrayList<Object> myList = new ArrayList<>();
    public void setObject(ArrayList<Object> myList);

}

public class Position implements CallableStatement
{
    String departmentName;
    String departmentType;
    String departmentDescription;

    public Position()
    {
        array();
    }

    public void array()
    {
        ArrayList<Object> myList = new ArrayList<Object>();
        myList.add(departmentName);
        myList.add(departmentType);
        myList.add(departmentDescription);
    }


    @Override
    public void setObject(ArrayList<Object> myList) 
    {
        String query = "{call insertPositions(?,?,?)}";

        try(Connection con = DBUtil.getConnection(DBType.MYSQL);
            java.sql.CallableStatement cs = con.prepareCall(query);)
                                    //Prepare the stored procedure call
        {
            //Setting the parameters
            cs.setObject(1, myList.toString());
            cs.setObject(2, myList.toString());
            cs.setObject(3, myList.toString());
            cs.executeUpdate();
        }
        catch(SQLException e)
        {
            System.err.println("Error: "+e.getMessage());
            System.err.println("Error: "+e.getErrorCode());
            System.err.println("Error: "+e.getSQLState());
        }
    }
}

GUI:

private void addDepartmentBtnActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    String departmentName = tfDepartmentName.getText();
    String departmentType = tfDepartmentType.getText();
    String departmentDescription = tfDescription.getText();

    ArrayList<Object> addPositionsList = new ArrayList<Object>();
    addPositionsList.add(departmentName);
    addPositionsList.add(departmentType);
    addPositionsList.add(departmentDescription);

    CallableStatement cs = new Position();
    cs.setObject(addPositionsList);

} 

2 个答案:

答案 0 :(得分:1)

我认为这是问题,cs.setObject(1, myList.toString());,实际上,您将所有查询参数设置为myList.toString(),为每个参数提供输出:[a,b,c]
您可以使用myList.get(index#int)
PS:尝试在将对象插入列表时修复对象的位置,以避免其他顺序超出预期。

答案 1 :(得分:0)

cs.setObject(1, myList.toString());
cs.setObject(2, myList.toString());
cs.setObject(3, myList.toString());

可是:

myList.toString() = [a,b,c]

很明显,当你这样做时,你会得到[a,b,c] [a,b,c] [a,b,c]作为你的三个对象。

而是尝试

cs.setObject(1, myList.get(0).toString());
cs.setObject(2, myList.get(1).toString());
cs.setObject(3, myList.get(2).toString());