Execute multiple SQL statements in java

后端 未结 3 2127
[愿得一人]
[愿得一人] 2021-02-14 02:50

I want to execute a query in Java.

I create a connection. Then I want to execute an INSERT statement, when done, the connection is closed but I wan

3条回答
  •  [愿得一人]
    2021-02-14 03:06

    In the abscence of the schema or the data contained in each table I'm going to make the following assumptions:

    The table special_columns could look like this:

    column_name
    -----------
    column_1
    column_2
    column_3
    

    The table alldata2 could look like this:

    column_1  | column_2  | column_3
    ---------------------------------
    value_1_1 | value_2_1 | value_3_1
    value_1_2 | value_2_2 | value_3_2    
    

    The table alldata should, after inserts have, happened look like this:

    colname
    ---------
    value_1_1
    value_1_2
    value_2_1
    value_2_2
    value_3_1
    value_3_2
    

    Given these assumptions you can copy the data like this:

    try (
      Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl1", "test", "oracle")
    )
    {
      StringBuilder columnNames = new StringBuilder();
    
      try (
        Statement select = connection.createStatement();
        ResultSet specialColumns = select.executeQuery("SELECT column_name FROM special_columns");
        Statement insert = connection.createStatement()
      )
      {
        while (specialColumns.next())
        {
          int batchSize = 0;             
    
          insert.addBatch("INSERT INTO alldata(colname) SELECT " + specialColumns.getString(1) + " FROM alldata2"); 
    
          if (batchSize >= MAX_BATCH_SIZE)
          { 
            insert.executeBatch();
            batchSize = 0;
          }
        }
    
        insert.executeBatch();
      }
    

    A couple of things to note:

    • MAX_BATCH_SIZE should be set to a value based on your database configuration and the data being inserted.
    • this code is using the Java 7 try-with-resources feature to ensure the database resources are released when they're finished with.
    • you haven't needed to do a Class.forName since the service provider mechanism was introduced as detailed in the JavaDoc for DriverManager.

提交回复
热议问题