开发者

Oracle table(s) data to INSERT statements with JAVA

How can I get sql inserts from a oracle table with JAVA? Is there a Oracle API for it?

I need to store it in a file, the result file should have these examples lines:

-- INSERTING into TEST
Insert into "TEST" ("CODE","FAMILY","SUB_FAMILY","SEVERITY","STATUS","ANOMALY_DATE","DESCRIPTION",
"COMMENTS","VALUE0","VALUE1","VALUE2","VALUE3","VALUE4","VALUE5","VALUE6","VALUE7","VALUE8",
"VALUE9") values (1,'family1','subFamily11','bad','initial',to_date('0005-11-21','DD/MM/RR'),'someDescription',
'someComment','someValue','someValue','someValue','uselessValue','uselessValue',null,null,null,null,null);

the 开发者_运维百科example line was created with the export tool from Oracle SQl developer

Thks.


Use Toad for Oracle. You can save a query as insert statements, spreadsheet, CSV... about anything you can think of.


I would also use Toad, but not sure if it's free.
If really need to do it in Java, you must use JDBC and the MetaData of the result set to create your commends.
Here an example, just as an idea - it is NOT complete*

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:oci:@DB_ID", "user", "password");
try {
  PreparedStatement stmt = conn.prepareStatement("SELECT * FROM MY_TABLE");
  StringBuilder command = new StringBuilder();
  ResultSet rset = stmt.executeQuery();
  ResultSetMetaData meta = rset.getMetaData();
  int columns = meta.getColumnCount();
  command.append("INSERT (");
  for (int i = 1; i <= columns; i++) {
    if (i > 1) {
      command.append(',');
    }
    command.append(meta.getColumnName(i));
  }
  command.append(") VALUES (");
  int head = command.length();
  while(rset.next()) {
    for (int i = 1; i <= columns; i++) {
      if (i > 1) {
        command.append(',');
      }
      String value = rset.getString(i);
      if (value != null) {
        command.append('\'');
        command.append(value);
        command.append('\'');
      } else {
        command.append("NULL");
      }
    }
    command.append(")");
    System.out.println(command.toString());
    command.setLength(head);
  }
} finally {
  conn.close();
}

* missing error handling, type handling (assumed all data is String),...


How crucial is it that you have insert statements? The normal way to transfer data between Oracle databases is to use the DataPump utility. This comes with a PL/SQL API which can be manipulated programmatically. I posted a sample set of code for doing that in another recent thread.


I came across this question looking for a pure java implementation to generate the INSERT statements of a Oracle table. I found this piece of code that may be useful to someone that want to do it using just Java with JDBC without any tool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜