IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JDBC Java Discussion :

Probléme insertion d'un CLOB


Sujet :

JDBC Java

  1. #1
    Membre régulier
    Inscrit en
    Février 2008
    Messages
    686
    Détails du profil
    Informations forums :
    Inscription : Février 2008
    Messages : 686
    Points : 118
    Points
    118
    Par défaut Probléme insertion d'un CLOB
    Salut
    je voudrais inserer du contenu xml dans une table.
    J'ai utilisé le type XMLTYPE stocké comme un CLOB
    voici la requête de création de ma table:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    create table RECEPTION_TMP(NUM_ENR varchar2(20),DAT_REC date,contenu XMLType)
        XmlType contenu STORE AS CLOB;
    Pour du contenu xml pas grand, tout se passe bien.
    mais pour un contenu XML assez grand j'obtient l'erreure suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    java.sql.SQLException: ORA-01461: une valeur 'LONG' ne peut être liée que dans une colonne de type 'LONG'
     
    	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    	at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    	at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    	at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
    	at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    	at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
    	at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1168)
    'ai utilisé un classe que j'ai trouvé dans le site oracle:
    http://www.oracle.com/technology/sam...lejdbc10g.html

    le code de la classe est:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
     
     
     
     
     
     
    /*
     * @author  Savitha
     * @version 1.0
     *
     * Development Environment        :  Oracle JDeveloper 10g
     * Name of the Application        :  ClobManipulationIn10g.java
     * Creation/Modification History  :
     *
     *    Savitha     17-Mar-2004      Created.
     */
     
     
    // Java SQL classes
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
     
    // Oracle JDBC driver class
    import oracle.jdbc.OracleDriver;
     
    // Java IO classes
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
     
    //Java Util classes
    import java.util.Properties;
     
     /**
      * This class demonstrates the Oracle JDBC 10g enhanced features for inserting
      * and retrieving CLOB data from the database. Using the new features, large
      * data of more than 32765 bytes can be inserted into the database using the
      * existing PreparedStatement.setString() and PreparedStatement.getString()
      * methods.
      */
    public class ClobManipulationIn10g {
     
      /* Database Connection object */
      private Connection conn = null;
     
      /* Variables to hold database details */
      private String url      = null;
      private String user     = null;
      private String password = null;
     
      // Create a property object to hold the username, password and
      // the new property SetBigStringTryClob.
      private Properties props = new Properties();
     
      /* String to hold file name */
      private String fileName = null;
     
     /**
      * Default Constructor to instantiate and get a handle to class methods
      * and variables.
      */
      public ClobManipulationIn10g(String fileName) {
        this.fileName = fileName;
      }
     
      /**
       * Main runnable class.
       */
      public static void main(String[] args) throws SQLException {
     
        // Instantiate the main class.
        ClobManipulationIn10g clobManipulationIn10g =
                                new ClobManipulationIn10g("test.xml");
     
        // Load the Oracle JDBC driver class.
        DriverManager.registerDriver(new OracleDriver());
     
        // Load the database details into the variables.
        String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
        clobManipulationIn10g.url      = dbUrl;
     
        // Replace the username where the table 'clob_tab' was created.
        clobManipulationIn10g.user     = "user";
     
        // Replace the password of the username.
        clobManipulationIn10g.password = "pwd";
     
        // Populate the property object to hold the username, password and
        // the new property 'SetBigStringTryClob' which is set to true. Setting
        // this property allows inserting of large data using the existing
        // setString() method, to a CLOB column in the database.
        clobManipulationIn10g.props.put("user", clobManipulationIn10g.user );
        clobManipulationIn10g.props.put("password", clobManipulationIn10g.password);
        clobManipulationIn10g.props.put("SetBigStringTryClob", "true");
     
        // Check if the table 'CLOB_TAB' is present in the database.
        clobManipulationIn10g.checkTables();
     
        // Call the methods to insert and select CLOB from the database.
        clobManipulationIn10g.insertClob();
       // clobManipulationIn10g.selectClob();
        System.out.println("END...");
     
      }
     
     /*
      *  This method will insert the data into a CLOB column in the database.
      *  Oracle JDBC 10g has enhanced the existing PreparedStatement.setString()
      *  method for setting the data more than 32765 bytes. So, using setString(),
      *  it is now easy to insert CLOB data into the database directly.
      */
      private void insertClob() throws SQLException {
     
        // Create a PreparedStatement object.
        PreparedStatement pstmt = null;
     
        try {
          // Create the database connection, if it is closed.
          if ((conn==null)||conn.isClosed()){
            // Connect to the database.
            conn = DriverManager.getConnection( this.url, this.props );
          }
     
          // Create SQL query to insert data into the CLOB column in the database.
          String sql ="INSERT INTO RECEPTION_TMP (NUM_ENR,DAT_REC,CONTENU) VALUES (?,?,?)";
     
          // Read a big file(larger than 32765 bytes)
          String str = this.readFile();
     
          // Create the OraclePreparedStatement object
          pstmt = conn.prepareStatement(sql);
     
          // Use the same setString() method which is enhanced to insert
          // the CLOB data. The string data is automatically transformed into a
          // clob and inserted into the database column. Make sure that the
          // Connection property - 'SetBigStringTryClob' is set to true for
          // the insert to happen.
          pstmt.setString(1,"str");
          pstmt.setDate(2,null);
          pstmt.setString(3,str);
     
          // Execute the PreparedStatement
          pstmt.executeUpdate();
     
        } catch (SQLException sqlex) {
        	sqlex.printStackTrace();
            // Catch Exceptions and display messages accordingly.
            System.out.println("SQLException while connecting and inserting into " +
                               "the database table: " + sqlex.toString());
        } catch (Exception ex) {
            System.out.println("Exception while connecting and inserting into the" +
                               " database table: " + ex.toString());
        } finally {
            // Close the Statement and the connection objects.
            if (pstmt!=null) pstmt.close();
            if (conn!=null)   conn.close();
        }
      }
     
     /*
      * This method reads the CLOB data from the database by using getString()
      * method.
      */
      private void selectClob() throws SQLException {
     
        // Create a PreparedStatement object
        PreparedStatement pstmt = null;
     
        // Create a ResultSet to hold the records retrieved.
        ResultSet rset = null;
        try {
          // Create the database connection, if it is closed.
          if ((conn==null)||conn.isClosed()){
            // Connect to the database.
            conn = DriverManager.getConnection( this.url, this.props );
          }
     
          // Create SQL query statement to retrieve records having CLOB data from
          // the database.
          String sqlCall = "SELECT clob_col FROM clob_tab";
          pstmt= conn.prepareStatement(sqlCall);
     
          // Execute the PrepareStatement
          rset = pstmt.executeQuery();
     
          String clobVal = null;
     
          // Get the CLOB value from the resultset
          while (rset.next()) {
            clobVal = rset.getString(1);
            System.out.println("CLOB length: "+clobVal.length());
          }
     
        } catch (SQLException sqlex) {
            // Catch Exceptions and display messages accordingly.
            System.out.println("SQLException while connecting and querying the " +
                               "database table: " + sqlex.toString());
        } catch (Exception ex) {
            System.out.println("Exception while connecting and querying the " +
                               "database table: " + ex.toString());
        } finally {
            // Close the resultset, statement and the connection objects.
            if (rset !=null) rset.close();
            if (pstmt!=null) pstmt.close();
            if (conn!=null)  conn.close();
        }
      }
     
      /**
       * Method to check if the table ('CLOB_TAB') exists in the database; if not
       * then it is created.
       *
       * Table Name: CLOB_TAB
       *   Column Name               Type
       *   -----------------------------------
       *   col_col                  CLOB
       */
      private void checkTables()   {
     
        Statement stmt = null;
        ResultSet rset = null;
        try {
     
          // Create the database connection, if it is closed.
          if ((conn==null)||conn.isClosed()){
            // Connect to the database.
            conn = DriverManager.getConnection( this.url, this.props );
          }
     
          // Create Statement object
          stmt = conn.createStatement();
     
          // Check if the table is present
          rset = stmt.executeQuery(" SELECT table_name FROM user_tables "+
                                   " WHERE table_name = 'CLOB_TAB' ");
     
          // If the table is not present, then create the table.
          if (!rset.next()) {
            // Table does not exist, create it
            stmt.executeUpdate(" CREATE TABLE clob_tab(clob_col CLOB)");
          }
     
        } catch (SQLException sqlEx) {
            System.out.println("Could not create table clob_tab : "
                                +sqlEx.toString());
        } finally  {
          try {
            if( rset != null ) rset.close();
            if( stmt != null ) stmt.close();
            if (conn!=null)  conn.close();
          } catch(SQLException ex) {
              System.out.println("Could not close objects in checkTables method : "
                                  +ex.toString());
          }
        }
      }
     
     /*
      * This method reads the specified text file and, returns the content
      * as a string.
      */
      private String readFile()
        throws FileNotFoundException, IOException{
     
          // Read the file whose content has to be passed as String
          BufferedReader br = new BufferedReader(new FileReader(fileName));
          String nextLine = "";
          StringBuffer sb = new StringBuffer();
          while ((nextLine = br.readLine()) != null) {
     
            sb.append(nextLine);
          }
          // Convert the content into to a string
          String clobData = sb.toString();
     
          // Return the data.
          return clobData;
      }
    }

  2. #2
    Membre expérimenté
    Avatar de yotta
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Septembre 2006
    Messages
    1 088
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Technicien maintenance
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2006
    Messages : 1 088
    Points : 1 540
    Points
    1 540
    Par défaut Si je ne me trompe pas
    A la lecture de votre code effectivement, on se demande pourquoi. D'autant qu'un champ CLOB sous Oracle permet le stockage de 4Go de caractères.
    Bref, je penses que cela vient de votre méthode d'écriture.
    D'après ce que j'en sait, pour écrire dans un champ CLOB avec Oracle, il faut utiliser un objet spécifique java.sql.Types.CLOB hors vous utilisez une chaîne String.
    Bref, je penses que la réponse à votre problème se trouve là :

    http://publib.boulder.ibm.com/infoce...d/cjvjdlbv.htm

Discussions similaires

  1. [debutant][Applet] problèmes insertion applet java
    Par mlequim dans le forum Applets
    Réponses: 5
    Dernier message: 11/07/2005, 09h50
  2. [ZEOSLIB] Problème Insertion dans une table
    Par moscovisci dans le forum Bases de données
    Réponses: 1
    Dernier message: 09/06/2005, 12h05
  3. [javascript] problème insertion image
    Par Pwill dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 18/05/2005, 16h12
  4. Réponses: 5
    Dernier message: 12/04/2005, 09h45
  5. problème insertion
    Par sonialem2000 dans le forum Bases de données
    Réponses: 5
    Dernier message: 14/07/2004, 01h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo