Search code examples
mysqlsqljavadb

Java DB select specific column on specific row


First post ever here :) looking franticly for help.

What I'm trying to do is to retrieve a specific image stored as blob in my database. I can't figure out why this query is not executing, I'm getting an exception as soon as I reach the executeQuery statement.

My table is:

Name xcoordinate ycoordinate vista firstscree 0 0 imag secondscreen 0 1 img2 ... etc.

ResultSet rs = null;
Statement stmnt = null;
Connection con = null;

String host = ...
String unm = ...
String pswrd = ...

BufferedImage imgt = null;
InputStream fis = null;
int xcoord;
int ycoord;
int newcoord;

 String SQLNorth = "select vista from location where xcoordinate = "+xcoord+" and ycoordinate = "+newcoord;
            newcoord = ycoord + 1;
            System.out.println("New coord x and y are" + xcoord + newcoord);

            con = DriverManager.getConnection(host, unm, pswrd);
            stmnt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmnt.executeQuery(SQLNorth);
            rs.next();  
            fis = rs.getBinaryStream(1);
            imgt = javax.imageio.ImageIO.read(fis);
        Image newImg = SwingFXUtils.toFXImage(imgt, null);
        img_1.setImage(newImg);

Solution

  • My guess is that it has something to do with the way you're building the query. Try using a prepared statement instead.

    ResultSet rs = null;
    PreparedStatement stmnt = null;
    Connection con = null;
    
    String host = ...
    String unm = ...
    String pswrd = ...
    
    BufferedImage imgt = null;
    InputStream fis = null;
    int xcoord;
    int ycoord;
    int newcoord;
    
    String SQLNorth = "select vista from location where xcoordinate = ? and ycoordinate = ?";
    
    newcoord = ycoord + 1;
    System.out.println("New coord x and y are" + xcoord + newcoord);
    
    con = DriverManager.getConnection(host, unm, pswrd);
    
    stmnt = con.prepareStatement(SQLNorth);
    stmnt.setInt(1, xcoord);
    stmnt.setInt(2, newcoord);
    
    rs = stmnt.executeQuery(SQLNorth);
    rs.next();  
    fis = rs.getBinaryStream(1);
    imgt = javax.imageio.ImageIO.read(fis);
    Image newImg = SwingFXUtils.toFXImage(imgt, null);
    img_1.setImage(newImg);