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; import java.sql.BatchUpdateException; public class BD_Image { // Insérer une image dans la Base de Données SQL Server public static void main(String[] args)throws Exception { System.out.println ("1"); Connection conn=null; FileInputStream fis = null; System.out.println ("2"); try { System.out.println ("3"); // Connexion à la Base de données SQL Server conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Cours", "user", ""); conn.setAutoCommit(false); System.out.println ("4"); System.out.println ("connexion reussi"); String req = "INSERT INTO Test (nom, prix, image) VALUES (?, ?, ?)"; // Préparer l'instruction SQL PreparedStatement pstmt = conn.prepareStatement(req); File image = new File("D:/logo.gif"); fis = new FileInputStream(image); // Insertion de nom pstmt.setString(1, "mon Nom"); // Insertion de prix pstmt.setInt(2, 1500); // Insertion d'image pstmt.setBinaryStream(3, fis, (int) image.length()); // Excécuter la requête pstmt.executeUpdate(); conn.commit(); } catch(Exception ex) { conn.rollback(); ex.printStackTrace(); } finally { conn.close(); fis.close(); } } } /* Requête création de la table USE [Cours] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE IF NOT EXISTS [dbo].[Test]( [Id] [int] NULL, [Nom] [varchar](250) NULL, [Prix] [int] NULL, [image] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO SET ANSI_PADDING OFF GO */ |