怎么将java中list中的数据序列化到数据库中,方便存取?
巴扎黑
巴扎黑 2017-04-17 11:31:08
0
3
843

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

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

巴扎黑
巴扎黑

reply all(3)
Ty80

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

左手右手慢动作

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!

PHPzhong

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template