Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
        Statement st = conn.createStatement();

        st.executeUpdate("create table images (Id int, b BLOB);");

        File file = new File("myimage.gif");
        FileInputStream fis = new FileInputStream(file);
        PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
        ps.setString(1, "10");
        ps.setBinaryStream(2, fis);
        ps.executeUpdate();

        ResultSet rset = st.executeQuery("select b from images");
        InputStream stream = rset.getBinaryStream(1);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int a1 = stream.read();
        while (a1 >= 0) {
            output.write((char) a1);
            a1 = stream.read();
        }
        Image myImage = Toolkit.getDefaultToolkit().createImage(output.toByteArray());
        output.close();

        ps.close();

        fis.close();
        st.close();
        conn.close();
    }

    private static Connection getConnection() throws Exception {
        Class.forName("org.hsqldb.jdbcDriver");
        String url = "jdbc:hsqldb:mem:data/tutorial";

        return DriverManager.getConnection(url, "sa", "");
    }
}