Inserting records into a MySQL table using Java

后端 未结 4 2118
北海茫月
北海茫月 2021-02-13 14:45

I created a database with one table in MySQL:

CREATE DATABASE iac_enrollment_system;

USE iac_enrollment_system;

CREATE TABLE course(
    course_code CHAR(7),
          


        
4条回答
  •  后悔当初
    2021-02-13 15:12

    This should work for any table, instead of hard-coding the columns.

    //Source details
        String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";
        String sourceUserName = "src";
        String sourcePassword = "***";
    
        // Destination details
        String destinationUserName = "dest";
        String destinationPassword = "***";
        String destinationUrl = "jdbc:mysql://server:3306/db";
    
        Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
        Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
    
        PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");
        ResultSet rs = sourceStatement.executeQuery();
        rs.setFetchSize(1000); // not needed
    
    
        ResultSetMetaData meta = rs.getMetaData();
    
    
    
        List columns = new ArrayList<>();
        for (int i = 1; i <= meta.getColumnCount(); i++)
            columns.add(meta.getColumnName(i));
    
        try (PreparedStatement destStatement = destConnection.prepareStatement(
                "INSERT INTO dest_table ("
                        + columns.stream().collect(Collectors.joining(", "))
                        + ") VALUES ("
                        + columns.stream().map(c -> "?").collect(Collectors.joining(", "))
                        + ")"
                )
        )
        {
            int count = 0;
            while (rs.next()) {
                for (int i = 1; i <= meta.getColumnCount(); i++) {
                    destStatement.setObject(i, rs.getObject(i));
                }
                
                destStatement.addBatch();
                count++;
            }
            destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
            System.out.println("done " + count);
    
        }

提交回复
热议问题