Convert String into Blob

I'm new to JDBC and stack overflow as well, and what I'm trying to do here is this :

I'm trying to insert a string as blob into a database but I'm getting null pointer exception. Here is the code I'm using :

public String execute() {
    String success="Success";
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://panorama-pc:3306/sample", "sample", "sample123");
        String sql = "Insert into users values(?,?,?,?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setNull(1, Types.NULL);  
        ps.setString(2,name);
        ps.setString(3,RollNo);
        ps.setString(4, date);

        Blob blob = con.createBlob();

        blob.setBytes(1,desc.getBytes()); // getting exception here 

        int i = ps.executeUpdate();
        if(i>0){
            return SUCCESS;
        }
        else{
            return ERROR;
        }
    }
    catch(SQLException | ClassNotFoundException e){
        e.printStackTrace();
    }       

Here desc is a string and I'm trying to insert it into a blob column. Can someone please help me out ?

Jon Skeet
people
quotationmark

A few possible problems:

  • It's not clear why you're explicitly setting a parameter to null. Why not just specify the column names explicitly in the SQL (which will make it clearer) and omit that column/parameter?
  • Although you're creating the blob, you're never using it as a parameter in your statement. You need ps.setBlob(...) somewhere
  • Your call to String.getBytes doesn't specify a Charset; I would strongly advise you to do so
  • You're not closing either the connection or the statement. Ideally, do so with a try-with-resources statement

For the NullPointerException... you haven't said where the exception occurs, but if desc is null, that would explain it - consider what you want your blob to contain in that case (or whether you should set the parameter to null).

people

See more on this question at Stackoverflow