guardar imagen en base de datos mysql blob ide netbeans

1
Java: Guardar Imagen en Base de Datos Mysql, BLOB Requisitos: - MySql - Una tabla en la Base de Datos que tenga un Campo de tipo LONGBLOB. 1 2 3 4 5 6 7 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Blob; import java.sql.PreparedStatement; import java.sql.SQLException; 1 2 3 4 5 6 7 8 9 10 11 12 13 public void guardaImagen(String ruta) throws SQLException, FileNotFoundException { String sql = "INSERT INTO imagen(Imagen) VALUES (?)"; //Creamos una cadena para después prepararla PreparedStatement stmt = conexion.prepareStatement(sql); File imagen = new File(ruta); //ruta puede ser: "/home/cmop/Desktop/1.jpg" FileInputStream fis = new FileInputStream(imagen); //Lo convertimos en un Stream stmt.setBinaryStream(1, fis, (int) imagen.length()); //Asignamos el Stream al Statement stmt.execute(); } La clave para realizarlos está en la asignación del Stream. Bueno espero haber contestado a los lectores y a mi compañero Vicuxero albeferz. Saludos a todos.

Upload: omarzinho-burgos-palacios

Post on 26-Jul-2015

578 views

Category:

Education


1 download

TRANSCRIPT

Page 1: Guardar imagen en base de datos mysql blob IDE NETBEANS

Java: Guardar Imagen en Base de

Datos Mysql, BLOB

Requisitos:

- MySql

- Una tabla en la Base de Datos que tenga un Campo de tipo LONGBLOB.

1

2

3

4

5

6

7

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Blob; import java.sql.PreparedStatement; import java.sql.SQLException;

1

2

3

4

5

6

7

8

9

10

11

12

13

public void guardaImagen(String ruta) throws SQLException, FileNotFoundException { String sql = "INSERT INTO imagen(Imagen) VALUES (?)"; //Creamos una cadena para después prepararla PreparedStatement stmt = conexion.prepareStatement(sql); File imagen = new File(ruta); //ruta puede ser: "/home/cmop/Desktop/1.jpg" FileInputStream fis = new FileInputStream(imagen); //Lo convertimos en un Stream stmt.setBinaryStream(1, fis, (int) imagen.length()); //Asignamos el Stream al Statement stmt.execute(); }

La clave para realizarlos está en la asignación del Stream.

Bueno espero haber contestado a los lectores y a mi compañero Vicuxero albeferz.

Saludos a todos.