Java SQL Table exportTableData(String tableName, Connection con)

Here you can find the source of exportTableData(String tableName, Connection con)

Description

export Table Data

License

Open Source License

Declaration

public static String exportTableData(String tableName, Connection con) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.sql.Connection;
import java.sql.DatabaseMetaData;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static String exportTableData(String tableName, Connection con) {

        String sqlString = null;//w  w w. j  ava 2s.co m

        try {
            DatabaseMetaData dbm = con.getMetaData();
            String[] types = { "TABLE" };
            ResultSet tables = dbm.getTables(null, null, null, types);

            while (tables.next()) {

                Statement stmt = con.createStatement();
                ResultSet rs = null;
                ResultSetMetaData metaData = null;
                int count;

                sqlString = "/* Tabelle " + tableName + " loeschen */\n";
                sqlString += "DELETE FROM " + tableName + ";\n\n";

                rs = stmt.executeQuery("SELECT * FROM " + tableName);
                metaData = rs.getMetaData();
                count = metaData.getColumnCount();

                sqlString += "/* Tabelle " + tableName + " fuellen */\n";

                int z = 0;
                while (rs.next()) {
                    sqlString += "INSERT INTO " + tableName + "\n";
                    sqlString += "\tVALUES( ";
                    for (int i = 1; i <= count; i++) {
                        sqlString += "'" + rs.getString(i) + "'";
                        if (i != count)
                            sqlString += ",  ";
                    }
                    sqlString += ");\n";
                    z++;
                }

                if (z == 0) {
                    sqlString += "/* Tabelle " + tableName + " enthaelt keine Daten! */\n";
                }
                sqlString += "\n";
            }

            sqlString += "\n\n";

        } catch (SQLException e) {
            sqlString = e.getMessage();
        }

        return sqlString;
    }
}

Related

  1. createTableAndInsertData(Connection c)
  2. dropTable(String tableName, Connection con)
  3. dumpTable(Connection conn, String TableName, PrintWriter out)
  4. dumpTable(Connection connection, String tablename)
  5. dumpTableToFile(Connection con, String table, String fileName)
  6. getAllTableNames(Connection connection)
  7. getAllTables(Connection conn)
  8. getBatchResultMessage(String tableName, int rowIdx, int resultCode)
  9. getCount(Connection conn, String tableName)