简体   繁体   中英

Java save JavaObjects in sql database

I'm trying to save a Java Object in my SQL Database but im getting an errory I cannot solve ...

stat.executeUpdate("CREATE Table users( id INT UNIQUE NOT NULL AUTO_INCREMENT,name char(50), pw char(50), messages LONGBLOB, profile LONGBLOB )");

. . .

public static void registerNewUser(String name , String pw , Profile profile){PreparedStatement ps=null;


        ps = con.prepareStatement("insert into users(name,pw,profile) VALUES(?,?,?)");
        ps.setString(1, name);
        ps.setString(2, pw);
        ps.setObject(3, (Object)profile);
        ps.executeUpdate();}

and finally it says

SQL Exception : Unknown SQL Type for PreparedStatement.setObject (SQL Type=1111
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setObject(Unknown Source)

Hope anybody can help me :D Thx in advance

ps the profile class

public class Profile implements Serializable{
private String name;
private int idNumber;
private byte[] picture;
private String password;

public Profile(String n, int i, byte[] p, String pw) {
    this.name = n;
    this.idNumber = i;
    this.picture = p;
    this.password = pw;
}

public String getProfileName(){
    return this.name;
}
public int getIDNumber(){
    return this.idNumber;
}
public byte[] getProfilePicture(){
    return this.picture;
}
public String getPassword(){
    return this.password;
}

public void setIDNumber(int number){
    this.idNumber = number;
}

}

Fixed by just using ps.setBytes(3,byte[]);

使用st.setBinaryStream(byte[])代替st.setObject()保存配置文件流。

Check out Hibernate and UserType . Do not let you scare off by it. Once you learn it you can do all those things with ease.

If you still want to go for jdbc use the following. Create a new ObjectOutputStream using an ArrayOutputStream. Now write your serializable object directly to the ObjectOutputStream and close it. Now use the underlying ArrayOutputStream to get the byte [] array representation of those data and just give the JDBC statement this byte array as value for your bLOB.

This should solve your problem. Actually this can be extracted to an utility class and used everywhere where you try to store serialized information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM