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 ?
A few possible problems:
ps.setBlob(...)
somewhereString.getBytes
doesn't specify a Charset
; I would strongly advise you to do soFor 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).
See more on this question at Stackoverflow