How to upload file in database? - java

I am trying to upload an image file with the code below, but the file is not being uploaded. The console still shows the message "1 Record Successfully Inserted."
Create table image
(
name varchar2(20),
photo blob
);
import java.sql.*;
import java.io.*;
public class ImageWriter {
static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "SYSTEM", "SYSTEM");
PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");
FileInputStream fin = new FileInputStream("E:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin,fin.available());
int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");
connection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

The above code works fine.
I dont know how you verified the contents of database.
Here is my code to verify the db(blob column): Try with this method. I used your code to insert the image and I could retrieve the image successfully. (note : file extension should be same)
public static void getPic() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "sys as sysdba",
"Oracle123");
ResultSet rs = null;
Statement stmt = null;
oracle.sql.BLOB photo = null;
conn.setAutoCommit(false);
stmt = conn.createStatement();
String name="ABC";
rs = stmt.executeQuery("select photo from image where name = '" + name + "'" );
rs.next();
photo = ((OracleResultSet) rs).getBLOB(1);
File f = new File("E:/image2.jpg");
f.getParentFile().mkdirs();
f.createNewFile();
InputStream in = photo.getBinaryStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream outputStream = new FileOutputStream(f);
int bufferSize = 1024;
int length = (int) photo.length();
byte[] buffer = new byte[bufferSize];
while((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
out.writeTo(outputStream);
System.out.println("Image Retrieved");
out.close();
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

Related

Print SQL table with java

I cant print SQL table with JAVA. I think JDBC Connection is not a problem. How can I print table in console??
Connection conn = null;
Statement stmt = null;
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
String user = "system";
String pwd = "SSTTaarr00119922";
ResultSet rs = null;
I did drivermanager getconnection.
System.out.println("start Connection");
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM dept";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
I cant print while func.
In your code, you are missing the catch in try---catch block. The code below is worked with SQL Server
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
System.out.println("start Connection");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=xxx;", "yyy", "zzz");
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM [dbo].[User]";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
}

Download blob data in a zip file in a simple java program

I'm not able to download the files using the below code as i have multiple types of extensions to download and i want to zip all the files and download. If i run the below code, it says files is corrupted. someone please help on this?
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcReadFile {
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
String url = "jdbc:oracle:thin:#xxx:xxxx:xxx";
String user = "xxx";
String password = "xxx";
String filePath = "C:/abc.vsd";
try {
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT DOC_BO FROM table fetch first 10 rows only";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("DOC_BO");
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File saved");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
No front end is required for this. Issue is resolved using the below code.
public class BlobDataExtract {
static ZipOutputStream zos = null;
static String url = "jdbc:oracle:thin:#hostname:1521:SID";
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql = "select Blob_Data,ORIG_NM from table";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
byte[] docBlob = null;
String filename = null;
FileOutputStream fos = new FileOutputStream("C:/Users/test.zip");
zos = new ZipOutputStream(fos);
while (rs.next()) {
docBlob = rs.getBytes("Blob_Data");
filename = rs.getString("ORIG_NM");
try {
zos.putNextEntry(new ZipEntry(filename));
zos.write(docBlob, 0, docBlob.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
}
}

Result set closed exception when trying to read a pdf file from sqlite table

I am trying to read a pdf file that has been stored in a table on SQLite database. when I run the Code it says ' Resultset is closed'.
public void syllabusAttach(){
String selectSQL = "SELECT Image_Reg FROM "+getRegulation()+" WHERE SubjectCode="+getSubCode()+"";
ResultSet rs = null;
FileOutputStream fos = null;
Connection conn = null;
Statement stmt = null;
try {
conn = connect();
stmt = conn.createStatement();
rs = stmt.executeQuery(selectSQL);
// write binary stream into file
InputStream is =rs.getBinaryStream("Image_Reg");
File file = new File("syllabus_"+getRegulation()+".pdf");
OutputStream os = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
byte[] content = new byte[1024];
int size = 0;
while((size = is.read(content)) !=-1){
os.write(content,0,size);
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
if (fos != null) {
fos.close();
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
}
}
}
write binary stream into file
File file = new File("syllabus_"+getRegulation()+".pdf");
fos = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("Image_Reg");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
fos.write(buffer);
}
}
When I did the above changes to the code, I could see that the files are being generated but when I open them it says "this file cannot be opened"
I found that the getSubCode() in the SQl query is not returning a the desired string which is leading to the error.

Changed image color after fetch from database

I have problem with fetching image from database in Java. I wrote this function:
public byte[] fetchPhoto(Long id) throws SQLException {
Connection conn = DataSourceUtils.getConnection(dataSource);
byte[] photo = null;
Blob imageBlob = null;
try (ResultSet rs = conn.createStatement()
.executeQuery("select IMAGE from IMAGE_TABLE where IMAGE_ID = " + id)) {
while (rs.next()) {
imageBlob = rs.getBlob(1);
photo = imageBlob.getBytes(1, (int) imageBlob.length());
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return photo;
}
Ok, I have fetched image, but effect is like :
this
Orginal image
here
I don't know why after fetch I have this color. I checked this image in database so here is ok.
Maybe you need solution like here. So using this example, here is your improved method:
public byte[] fetchPhoto(Long id) throws SQLException {
Connection conn = DataSourceUtils.getConnection(dataSource);
byte[] photo = null;
Blob imageBlob = null;
try (ResultSet rs = conn.createStatement()
.executeQuery("select IMAGE from IMAGE_TABLE where IMAGE_ID = " + id)) {
while (rs.next()) {
imageBlob = rs.getBlob(1);
photo = imageBlob.getBytes(1, (int) imageBlob.length());
ByteArrayInputStream bais = new ByteArrayInputStream(photo);
BufferedImage bf = ImageIO.read(bais);
BufferedImage nbf = new BufferedImage(bf.getWidth(),
bf.getHeight(), BufferedImage.TYPE_INT_RGB);
nbf.createGraphics().drawImage(bf, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(nbf, "jpg", baos);
photo = baos.toByteArray();
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return photo;
}
If I were you I moved this code to separete method.

How do I store and retrieve a BLOB type from sqlite?

I have a java class (Shell) that stores all the information I need to load for my application. Currently, it is saved into a .txt file and loaded from said file.
This class is responsible for saving and loading the Shell:
public void saveShell() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
new FileOutputStream(getPath()));
objectOutputStream.writeObject(new Date());
objectOutputStream.writeBoolean(true);
objectOutputStream.writeFloat(1.0f);
objectOutputStream.writeObject(shl);
objectOutputStream.flush();
objectOutputStream.close();
System.out.println("Successfully saved");
}
public Shell loadShell() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(
new FileInputStream(getPath()));
Date date = (Date) objectInputStream.readObject();
System.out.println(date);
System.out.println(objectInputStream.readBoolean());
System.out.println(objectInputStream.readFloat());
Shell readShell = (Shell) objectInputStream.readObject();
System.out.println("Shell Loaded");
objectInputStream.close();
System.out.println("Object output stream closed");
return readShell;
}
However, now that I'm trying to distribute the application, using a file seems less viable than using a database so I have already set up SQLite.
Since Shell has everything I need, I'd like to store it as a BLOB and be able to retrieve the object later. I am new to databases so I don't quite know the specific java methods that I should use. I know that this question is very similar to How do i store and retrieve a blob from sqlite but its answer is in C#. Plus, most examples I've found are always storing pictures and images with a certain URL, there aren't many examples with objects.
I got it working. Basically I added two functions: saveShellDB and loadShellDB:
public void saveShellDB() throws ClassNotFoundException, IOException {
Class.forName(classForName);
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(connectionPath);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
File file = new File("shell.txt");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = connection.prepareStatement("INSERT INTO shell (name, shl) VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, (int)file.length());
ps.executeUpdate();
ps.close();
fis.close();
System.out.println("SQL save done");
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
public void loadShellDB() throws ClassNotFoundException, SQLException, IOException {
Class.forName(classForName);
Connection conn = DriverManager.getConnection(connectionPath);
String sql = "SELECT name, shl FROM shell";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
File shl = new File(fileOutputPath);
FileOutputStream fos = new FileOutputStream(shl);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(2);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
conn.close();
System.out.println("SQL Load Done");
}
Then, I just had to call them from my old save functions:
public void saveShell() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
new FileOutputStream(getPath()));
objectOutputStream.writeObject(new Date());
objectOutputStream.writeBoolean(true);
objectOutputStream.writeFloat(1.0f);
objectOutputStream.writeObject(shl);
objectOutputStream.flush();
objectOutputStream.close();
System.out.println("Successfully saved");
saveShellDB(); //here!
}
public Shell loadShell() throws FileNotFoundException, IOException, ClassNotFoundException {
loadShellDB(); //here!
ObjectInputStream objectInputStream = new ObjectInputStream(
new FileInputStream(getPath()));
Date date = (Date) objectInputStream.readObject();
System.out.println(date);
System.out.println(objectInputStream.readBoolean());
System.out.println(objectInputStream.readFloat());
Shell readShell = (Shell) objectInputStream.readObject();
System.out.println("Shell Loaded");
objectInputStream.close();
System.out.println("Object output stream closed");
return readShell;
}

Categories

Resources