search

Home  >  Q&A  >  body text

怎么将java中list中的数据序列化到数据库中,方便存取?

rt.
怎么将java中list中的数据序列化到数据库中,方便存取?
我想讲一个list集合 直接放在一个varchar字段中,而不像新增一个表来专门存在list中数据,我该怎么做?

ps:之前我用php的时候会用serialize去序列化数组,但java我该怎么做?

巴扎黑巴扎黑2821 days ago878

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:33:08

    Convert the java list into json format and store it in the database

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:33:08

    public List getObject(String sql, Object[] object) { //SQL execution statement, object is the parameter in your sql statement
    List list = new ArrayList();
    Connection con = null;
    PreparedStatement pre = null;
    ResultSet rs = null;
    try{
    con = C3P0Util.getInstance().getConnection(); //This is how you get the database connection, you change this to call The jdbc method you wrote yourself
    pre = con.prepareStatement(sql); //Execute the sql statement
    if(object!=null){
    for(int i=0;i<object.length; i++){
    pre.setObject(i+1, object[i]); //Assign values ​​to the parameters in sql
    }
    }
    rs = pre.executeQuery();
    while(rs.next()){
    Users u = new User();
    u.setUserName(rs.getString("UserName"));
    u.setUserPas(rs.getString(" UserPas")); list.add(u);
    }
    }catch(Exception e){
    e.printStackTrace();
    return null;
    }finally{
    C3P0Util.close(con, pre, rs); //Close the database resource
    }
    return list; //Return the list collection
    }
    Note: The list stores the information of the User object
    If you want to get the information of the User object, you must traverse list
    for(int i=0;i<list.size;i++){
    User u = (User)list.get(i); System.out.println("UserName:"+u.getUserName());
    System.out.println("UserPas:"+u.getUserPas());
    } The above is for the list where there are many User object. Of course, it is also possible to have only one User object in the list.
    If there is only one User in your list, you can directly: User u = (User)list.get(0);
    System.out.println("UserName:"+u.getUserName());
    System.out.println("UserPas:"+u.getUserPas());

    Hope this helps!

    reply
    0
  • PHPz

    PHPz2017-04-17 11:33:08

    Hello, I didn’t understand your question clearly. I suggest you make the list more specific. If the list contains strings, this is easier to solve. If there are complex classes in this list, it depends on the specific requirements.

    reply
    0
  • Cancelreply