How to insert image to mysql database in netbeans java - java

I have poor knowledge about programming. I need to save image in MySQL database. I have created a database table and there is a column to add image with longblob data type.
I have code to a button to choose image from folder in PC then it load to a jlable. Now I need to insert this image to a database.
This is my code;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel1.setIcon(new ImageIcon(path));
try{
FileInputStream fin=new FileInputStream(f);
int len=(int)f.length(); Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:my­sql://localhost/hss", "root", "bis123");
PreparedStatement ps=con.prepareStatement("Insert into profile values(?)");
ps.setBinaryStream(1, fin, len);
int status=ps.executeUpdate();
if(status > 0) {
jLabel2.setText("Successfully inserted in DB");
}else{
jLabel2.setText("Image not inserted!");
}
}catch(Exception e){
System.out.println(e);
}
}

In MySQL when we use the blob type to store the data , it support only 5 kb image capacity.
CREATE TABLE image (
id varchar(45) DEFAULT NULL,
size int(11) DEFAULT NULL,
image longblob
);
created database table in above code
this is java code to insert image in database
import java.sql.*;
import java.io.*;
public class InsertImagesMysql{
public static void main(String[] args){
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("pic.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre =
con.prepareStatement("insert into Image values(?,?,?)");
pre.setString(1,"test");
pre.setInt(2,3);
pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Successfully inserted the file into the database!");
pre.close();
con.close();
}catch (Exception e1){
System.out.println(e1.getMessage());
}
}
}
here is code to retrieve data from database
import java.io.*;
import java.sql.*;
public class RetriveImagesMysql{
public static void main(String[] args){
System.out.println("Retrive Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from image");
int i = 0;
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));
i++;
int c = 0;
while ((c = in.read()) > -1) {
f.write(c);
}
f.close();
in.close();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
here just assign fin to jbutton action event it will trigger automatically the run of the code

Related

how to read the content of the file and store in database using java

I need to read a file by column and I need to store it in a database. My problem is the file contents are not stored in the database and the code just read the contents. I am getting an error in storing it.
Code:
public class Test3 {
private static String vrms;
private static String irms;
private static String total;
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test3";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,password);
System.out.println("Connection Established");
return conn;
} catch (Exception e) {
System.out.println("Connection not established");
return null;
} }
public static void main(String[] args) throws Exception {
FileInputStream fstream = new FileInputStream("D:/data/database.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
strLine.split(" ");
System.out.println(strLine);
}
in.close();
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(strLine);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into meter1(vrms, irms, total) values (?, ?, ?)");
pstmt.setString(1, vrms);
pstmt.setString(2, irms);
pstmt.setString(3, total);
pstmt.executeUpdate();
conn.commit();
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}}}
error:
10 11 0
12 13 0
14 15 0
Connection Established
Error: null
java.lang.NullPointerException
at java.io.File.(Unknown Source)
at vidhya.Test3.main(Test3.java:71)
Exception in thread "main" java.lang.NullPointerException
at vidhya.Test3.main(Test3.java:85)
This is sample code which might be helpful..
Replace the column names with correct db columns.
public static void main(String[] args) throws IOException, SQLException {
PreparedStatement preparedstatement = null;
try{
String read=null;
in = new BufferedReader(new FileReader("patientlist.txt"));
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
name=splited[0];
age=splited[1];
height=splited[2];
weight=splited[3];
addpatient(connection, preparedstatement, name, age, height, weight);
}
}
catch (IOException e) {System.out.println("There was a problem: " + e);}
if (connection != null)
try{connection.close();} catch(SQLException ignore){}
}
public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age, String height, String weight) throws SQLException{
preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
preparedstatement.setString(1, name);
preparedstatement.setString(2, age);
preparedstatement.setString(3, height);
preparedstatement.setString(4, weight);
preparedstatement.executeUpdate();
}
You have not stored information read from the file in any variable (vrms, irms or total). Correct your code before posting here for the issue.
Posting the sample data file and column data types will be helpful.

Search for record in database "Java.lang.NullPointerExepton"

I want to search for the id of a movie in a table of the database. I'm new to database connection and new to java as well. This code doesn't have error in my form but I created a record of id '1' and always gives me this error "Java.lang.NullPointerExepton".
I have the record with that id but always have that error. Any help will be appreciated
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";
try{
String sql="SELECT Movie_idMovie FROM rental_movie"
+ "WHERE Movie_idMovie =?";
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
rs=pst.executeQuery();
if(rs.next()){
String add1=rs.getString("Movie_idMovie");
jTextField2.setText(add1);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
The problem here is this:
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";
pst=conn.prepareStatement(sql);
You missed the important step of actually opening the connection, leaving conn null when you try and use it. Try adding the following, before you call conn.prepare...
conn = DriverManager.getConnection(url, userid, password);

How to Insert/retrieve Images in SQL server 2008 R2, using Java code?

I work on a java program that needs to insert/retrieve from/to DB (SQL server 2008 R2). Can any one help me?
public void insertImage(Connection conn,String img)
{
int len;
String query;
PreparedStatement pstmt;
try
{
File file = new File(img);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into TableImage VALUES(?,?,?)");
pstmt = conn.prepareStatement(query);
pstmt.setString(1,file.getName());
pstmt.setInt(2, len);
// Method used to insert a stream of bytes
pstmt.setBinaryStream(3, fis, len);
pstmt.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getImageData(Connection conn)
{
byte[] fileBytes;
String query;
try
{
query = "select data from tableimage";
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(query);
if (rs.next())
{
fileBytes = rs.getBytes(1);
OutputStream targetFile=
new FileOutputStream(
"d://filepath//new.JPG");
targetFile.write(fileBytes);
targetFile.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

Retrieve an Image stored as BLOB on a MYSQL DB

I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.
Table name: IMAGENES_REGISTROS
BLOB Field name: IMAGEN
Any Ideas?
On your ResultSet call:
Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
Alternatively, you can call:
byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
As BalusC noted in his comment, you'd better use:
InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);
And then the code depends on how you are going to read and embed the image.
imagebytes = rs.getBytes("images");
image=getToolkit().createImage(imageBytes);
Image img = image.getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon=new ImageIcon(img);
jLabel6.setIcon(icon);
Try this code to get adjustable image from blog Mysql in netbeans
final String dbURL = "jdbc:mysql://localhost:3306/portfolio";
final String dbUser = "root";
final String dbPass = "";
Connection conn = null;
Statement stmt = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
System.out.println("db connected");
stmt = (Statement) conn.createStatement();
ResultSet rs1;
rs1 = stmt.executeQuery("select profileImage from tbl_welcome where id = 1117");
if (rs1.next()) {
byte[] imgData = rs1.getBytes("profileImage");//Here....... r1.getBytes() extract byte data from resultSet
System.out.println(imgData);
response.setHeader("expires", "0");
response.setContentType("image/jpg");
OutputStream os = response.getOutputStream(); // output with the help of outputStream
os.write(imgData);
os.flush();
os.close();
}
} catch (SQLException ex) {
// String message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void loadFileDataBlobFromDataBase()
{
List<Blob> bFile = jdbcTemplate.query(sql, new RowMapper<Blob>() {
#Override
public Blob mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getBlob(1);
}
});
if (bFile != null && bFile.size() > 0) {
bufReader = new BufferedReader(new InputStreamReader(bFile.get(
0).getBinaryStream()));
}
if (null != bufReader) {
dataVO record = null;
String lineStr = bufReader.readLine();
record = (dataVO) lineMapper.mapLine(lineStr, 1);
}
}
}

Can we fetch an added image from MySql database by using java?

I have added an image into a MySql database. And I am trying to fetch the image from the database by creating a new file by using java. The problem is that everything goes fine and image file has been created but the image file doesn't contain the image, it has just nothing and the size of the new created image file differs from the original one.....
The Sql Code:
CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `description` varchar(20) default NULL, `photo` blob, PRIMARY KEY (`id`) );
insert into pictures values('1','pic1','D:\java.jpg');
And the java code:
public class ReadBlobPicture
{
static String url = "jdbc:mysql://localhost:3306/imgdatabase";
static String username = "root";
static String password = "tiger";
public static void main(String[] args)
throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT photo FROM pictures where id=1";
Statement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery(sql);
Object obj = resultSet;
while (resultSet.next())
{
File image = new File("E:\\java12.jpg");
FileOutputStream fos = new FileOutputStream(image);
System.out.println(resultSet.getString(1));
byte[] buffer = new byte[1];
InputStream is2 = resultSet.getBinaryStream(1);
System.out.println(is2.available());
while (is2.read() > 0)
{
fos.write(buffer);
fos.flush();
}
fos.close();
}
conn.close();
}
}
You read from the stream, but never save the read character into the buffer...
while (is2.read() > 0)
{
fos.write(buffer);
fos.flush();
}
something like:
int x;
while((x = is2.read()) != -1)
{
fos.write(x);
}
fos.flush();
(edit - from the comment on another answer...)
For the insert statement not inserting the image see this link
/*
Defining the Table: Oracle and MySql
create table MyPictures (
id INT PRIMARY KEY,
name VARCHAR(0),
photo BLOB
);
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertPictureToMySql {
public static void main(String[] args) throws Exception, IOException, SQLException {
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";
FileInputStream fis = null;
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
File file = new File("myPhoto.png");
fis = new FileInputStream(file);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setString(1, "001");
ps.setString(2, "name");
ps.setBinaryStream(3, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
} finally {
ps.close();
fis.close();
}
}
}
you have a problem writing to your outputstream, it should be like this:
while ((buffer[0] = is2.read()) > 0)
{
fos.write(buffer[0]);
fos.flush();
}
And your picture should be saved in the database as a BLOB!
P.S. your buffer is useless since it has a size of 1, you should make it at least 512 or 1024 to void reading byte by byte.
Hope it helped.
insert into pictures values('1','pic1','D:\java.jpg');
Does not insert binary jpg data into the database, it inserts the string D:\java.jpg
// create a file called MySqlInsertBlob.java
//==========import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Blob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
class MySqlInsertBlob {
FileOutputStream image;
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt= null;
ResultSet res = null;
StringBuffer query=null;
String filename ="c:/backblue.gif";
public MySqlInsertBlob(){
try{
query=new StringBuffer("insert into blobs(filename,binarydata,name) values (?,?,?)");
File file= new File(filename);
Class.forName("com.mysql.jdbc.Driver")…
conn = DriverManager.getConnection("jdbc:mysql:…
stmt=conn.createStatement();
pstmt=conn.prepareStatement(query.toSt…
pstmt.setString(1, filename);
pstmt.setBinaryStream(2, new FileInputStream(filename),(int)file.leng…
pstmt.setString(3,"silviya");
pstmt.executeUpdate();
System.out.println("Successfully inserted into BLOBS .....");
ResultSet rs=stmt.executeQuery("select * from blobs where name='silviya'");
if (rs.next()) {
Blob test=rs.getBlob("binarydata");
InputStream x=test.getBinaryStream();
int size=x.available();
OutputStream out=new FileOutputStream("c:/xyz.gif");
byte b[]= new byte[size];
x.read(b);
out.write(b);
}
}catch(ClassNotFoundException cnfe){
System.out.println("ClassNotFoundExcep… occured :"+cnfe);
}catch(SQLException se){
System.out.println("SQLException occured :"+se);
}catch(FileNotFoundException fe){
System.out.println("File Not Found Exception occured :"+fe);
}catch(Exception e){
System.out.println("Exception occured :"+e);
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){}
}
Source(s):

Categories