<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Generating a database dump SQL Script from Java</title>
	<atom:link href="http://www.isocra.com/2004/10/dumptosql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.isocra.com/2004/10/dumptosql/</link>
	<description>Thoughts and tutorials on web design, Java, Javascript and project management</description>
	<lastBuildDate>Wed, 01 Feb 2012 09:44:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: bm</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1488</link>
		<dc:creator>bm</dc:creator>
		<pubDate>Thu, 16 Jun 2011 22:02:16 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1488</guid>
		<description>i made much more superious version of this algorithm.

Works only for postgres

generates tables,sequences, functions,indexes, fk, views, schemas, db dump

code:
&lt;pre&gt;
/**
 * Copyright Isocra Ltd 2004
 * You can use, modify and freely distribute this file as long as you credit Isocra Ltd.
 * There is no explicit or implied guarantee of functionality associated with this file, use it at your own risk.
 */


import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;


/**
 * This class connects to a database and dumps all the tables and contents out to stdout in the form of
 * a set of SQL executable statements
 */
public class db2sql {

    /** Dump the whole database to an SQL string */
    public static Strings dumpDB(Properties props) {
        String driverClassName = props.getProperty(&quot;driver.class&quot;);
        String driverURL = props.getProperty(&quot;driver.url&quot;);
        // Default to not having a quote character
        String columnNameQuote = props.getProperty(&quot;columnName.quoteChar&quot;, &quot;&quot;);
        DatabaseMetaData dbMetaData = null;
        Connection dbConn = null;
        try {
            Class.forName(driverClassName);
            dbConn = DriverManager.getConnection(driverURL, props);
            dbMetaData = dbConn.getMetaData();
        }
        catch( Exception e ) {
            System.err.println(&quot;Unable to connect to database: &quot;+e);
            return null;
        }
        try {
        	Strings strings = new Strings();
            Set schemas = new HashSet();
            String catalog = props.getProperty(&quot;catalog&quot;);
            String schema = props.getProperty(&quot;schemaPattern&quot;);
            String tables = props.getProperty(&quot;tableName&quot;);
            String[] types = {&quot;VIEW&quot;,&quot;TABLE&quot;};
            ResultSet rs = dbMetaData.getTables(catalog, schema, tables, types);
            if (! rs.next()) {
                System.err.println(&quot;Unable to find any tables matching: catalog=&quot;+catalog+&quot; schema=&quot;+schema+&quot; tables=&quot;+tables);
                rs.close();
            } else {
                // Right, we have some tables, so we can go to work.
                // the details we have are
                // TABLE_CAT String =&gt; table catalog (may be null)
                // TABLE_SCHEM String =&gt; table schema (may be null)
                // TABLE_NAME String =&gt; table name
                // TABLE_TYPE String =&gt; table type. Typical types are &quot;TABLE&quot;, &quot;VIEW&quot;, &quot;SYSTEM TABLE&quot;, &quot;GLOBAL TEMPORARY&quot;, &quot;LOCAL TEMPORARY&quot;, &quot;ALIAS&quot;, &quot;SYNONYM&quot;.
                // REMARKS String =&gt; explanatory comment on the table
                // TYPE_CAT String =&gt; the types catalog (may be null)
                // TYPE_SCHEM String =&gt; the types schema (may be null)
                // TYPE_NAME String =&gt; type name (may be null)
                // SELF_REFERENCING_COL_NAME String =&gt; name of the designated &quot;identifier&quot; column of a typed table (may be null)
                // REF_GENERATION String =&gt; specifies how values in SELF_REFERENCING_COL_NAME are created. Values are &quot;SYSTEM&quot;, &quot;USER&quot;, &quot;DERIVED&quot;. (may be null)
                // We will ignore the schema and stuff, because people might want to import it somewhere else
                // We will also ignore any tables that aren&#039;t of type TABLE for now.
                // We use a do-while because we&#039;ve already caled rs.next to see if there are any rows
                do {
                    String tableName = rs.getString(&quot;TABLE_NAME&quot;);
                    String tableType = rs.getString(&quot;TABLE_TYPE&quot;);
                    String tableSchema = rs.getString(&quot;TABLE_SCHEM&quot;);
                    String fullTableName = tableSchema+&quot;.&quot;+tableName;
                    schemas.add(tableSchema);
                    if (&quot;TABLE&quot;.equalsIgnoreCase(tableType)) {
                    	strings.initResult.append(&quot;\n\n-- &quot;+fullTableName);
                    	strings.initResult.append(&quot;\nCREATE TABLE &quot;+fullTableName+&quot; (\n&quot;);
                        ResultSet tableMetaData = dbMetaData.getColumns(null, null, tableName, &quot;%&quot;);
                        boolean firstLine = true;
                        while (tableMetaData.next()) {
                            if (firstLine) {
                                firstLine = false;
                            } else {
                                // If we&#039;re not the first line, then finish the previous line with a comma
                            	strings.initResult.append(&quot;,\n&quot;);
                            }
                            String columnName = tableMetaData.getString(&quot;COLUMN_NAME&quot;);
                            String columnType = tableMetaData.getString(&quot;TYPE_NAME&quot;);
                            // WARNING: this may give daft answers for some types on some databases (eg JDBC-ODBC link)
                            String decimalDigits = tableMetaData.getString(&quot;DECIMAL_DIGITS&quot;);
                            String columnSize = tableMetaData.getString(&quot;COLUMN_SIZE&quot;);
                            String columnPrecision;
                            
                            if(columnType.equals(&quot;varchar&quot;) ){
                            	columnPrecision = &quot; (&quot;+columnSize+&quot;)&quot;;
                            }else if(columnType.equals(&quot;numeric&quot;) &#124;&#124; columnType.equals(&quot;decimal&quot;)){
                            	if(Integer.parseInt(columnSize) &gt;1000)
                            		columnSize=&quot;1000&quot;;
                            	columnPrecision=&quot; (&quot;+columnSize+&quot;, &quot;+decimalDigits+&quot; )&quot;;
                            	
                            }else
                            	columnPrecision = &quot;&quot;;
                            
                            
                            String nullable = tableMetaData.getString(&quot;IS_NULLABLE&quot;);
                            String defaultValue = tableMetaData.getString(&quot;COLUMN_DEF&quot;);
                            if(defaultValue == null)
                            	defaultValue =&quot;&quot;;
                            else
                            	defaultValue =&quot; DEFAULT &quot;+defaultValue;
                            	
                            if(columnType.equalsIgnoreCase(&quot;SERIAL&quot;)){
                            	defaultValue=&quot;&quot;;
                            	columnSize=&quot;&quot;;
                            }
                            String nullString = &quot;NULL&quot;;
                            if (&quot;NO&quot;.equalsIgnoreCase(nullable)) {
                                nullString = &quot;NOT NULL&quot;;
                            }
                            strings.initResult.append(&quot;    &quot;+columnNameQuote+columnName+columnNameQuote+&quot; &quot;+columnType+columnPrecision+&quot;&quot;+&quot; &quot;+nullString+ defaultValue);
                        }
                        tableMetaData.close();

                        // Now we need to put the primary key constraint
                        Set pkNames = new HashSet();
                        try {
                            ResultSet primaryKeys = dbMetaData.getPrimaryKeys(catalog, schema, tableName);
                            // What we might get:
                            // TABLE_CAT String =&gt; table catalog (may be null)
                            // TABLE_SCHEM String =&gt; table schema (may be null)
                            // TABLE_NAME String =&gt; table name
                            // COLUMN_NAME String =&gt; column name
                            // KEY_SEQ short =&gt; sequence number within primary key
                            // PK_NAME String =&gt; primary key name (may be null)
                            String primaryKeyName = null;
                            StringBuffer primaryKeyColumns = new StringBuffer();
                            while (primaryKeys.next()) {
                                String thisKeyName = primaryKeys.getString(&quot;PK_NAME&quot;);
                                pkNames.add(thisKeyName);
                                if ((thisKeyName != null &amp;&amp; primaryKeyName == null)
                                        &#124;&#124; (thisKeyName == null &amp;&amp; primaryKeyName != null)
                                        &#124;&#124; (thisKeyName != null &amp;&amp; ! thisKeyName.equals(primaryKeyName))
                                        &#124;&#124; (primaryKeyName != null &amp;&amp; ! primaryKeyName.equals(thisKeyName))) {
                                    // the keynames aren&#039;t the same, so output all that we have so far (if anything)
                                    // and start a new primary key entry
                                    if (primaryKeyColumns.length() &gt; 0) {
                                        // There&#039;s something to output
                                    	strings.initResult.append(&quot;,\n CONSTRAINT &quot;+primaryKeyName+&quot; PRIMARY KEY &quot;);
                                    	
                                    	strings.initResult.append(&quot;(&quot;+primaryKeyColumns.toString()+&quot;)&quot;);
                                    }
                                    // Start again with the new name
                                    primaryKeyColumns = new StringBuffer();
                                    primaryKeyName = thisKeyName;
                                }
                                // Now append the column
                                if (primaryKeyColumns.length() &gt; 0) {
                                    primaryKeyColumns.append(&quot;, &quot;);
                                }
                                primaryKeyColumns.append(primaryKeys.getString(&quot;COLUMN_NAME&quot;));
                            }
                            if (primaryKeyColumns.length() &gt; 0) {
                                // There&#039;s something to output
                            	strings.initResult.append(&quot;,\n    CONSTRAINT &quot;+primaryKeyName+&quot; PRIMARY KEY &quot;);
                            	strings.initResult.append(&quot; (&quot;+primaryKeyColumns.toString()+&quot;)&quot;);
                            }
                        } catch (SQLException e) {
                            // NB you will get this exception with the JDBC-ODBC link because it says
                            // [Microsoft][ODBC Driver Manager] Driver does not support this function
                            System.err.println(&quot;Unable to get primary keys for table &quot;+tableName+&quot; because &quot;+e);
                        }
                        strings.initResult.append(&quot;\n);\n&quot;);
                        //and FK
                        try{
                        	ResultSet exportedKeys = dbMetaData.getExportedKeys(catalog, tableSchema, tableName);
                       
//                        	PKTABLE_CAT String =&gt; primary key table catalog (may be null) 
//                        	PKTABLE_SCHEM String =&gt; primary key table schema (may be null) 
//                        	PKTABLE_NAME String =&gt; primary key table name 
//                        	PKCOLUMN_NAME String =&gt; primary key column name 
//                        	FKTABLE_CAT String =&gt; foreign key table catalog (may be null) being exported (may be null) 
//                        	FKTABLE_SCHEM String =&gt; foreign key table schema (may be null) being exported (may be null) 
//                        	FKTABLE_NAME String =&gt; foreign key table name being exported 
//                        	FKCOLUMN_NAME String =&gt; foreign key column name being exported 
//                        	KEY_SEQ short =&gt; sequence number within foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key). 
//                        	UPDATE_RULE short =&gt; What happens to foreign key when primary is updated: 
//                        	importedNoAction - do not allow update of primary key if it has been imported 
//                        	importedKeyCascade - change imported key to agree with primary key update 
//                        	importedKeySetNull - change imported key to NULL if its primary key has been updated 
//                        	importedKeySetDefault - change imported key to default values if its primary key has been updated 
//                        	importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility) 
//                        	DELETE_RULE short =&gt; What happens to the foreign key when primary is deleted. 
//                        	importedKeyNoAction - do not allow delete of primary key if it has been imported 
//                        	importedKeyCascade - delete rows that import a deleted key 
//                        	importedKeySetNull - change imported key to NULL if its primary key has been deleted 
//                        	importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility) 
//                        	importedKeySetDefault - change imported key to default if its primary key has been deleted 
//                        	FK_NAME String =&gt; foreign key name (may be null) 
//                        	PK_NAME String =&gt; primary key name (may be null) 
//                        	DEFERRABILITY short =&gt; can the evaluation of foreign key constraints be deferred until commit 
//                        	importedKeyInitiallyDeferred - see SQL92 for definition 
//                        	importedKeyInitiallyImmediate - see SQL92 for definition 
//                        	importedKeyNotDeferrable - see SQL92 for definition 

                        while(exportedKeys.next()){
                        	String fkName = exportedKeys.getString(&quot;FK_NAME&quot;);
                        	String fKColumnName = exportedKeys.getString(&quot;FKCOLUMN_NAME&quot;);
                        	String pKColumnName = exportedKeys.getString(&quot;PKCOLUMN_NAME&quot;);
                        	String fKTableFullName = exportedKeys.getString(&quot;FKTABLE_SCHEM&quot;)+&quot;.&quot;+exportedKeys.getString(&quot;FKTABLE_NAME&quot;);
                        	
                        	strings.fkREsult.append(&quot;\n--fk for &quot;+fKTableFullName+&quot;\n&quot;);
                        	strings.fkREsult.append(&quot;\nALTER TABLE &quot;+fKTableFullName+&quot;\n&quot;);
                        	strings.fkREsult.append(&quot; ADD CONSTRAINT &quot;+fkName + &quot; FOREIGN KEY (&quot;+ fKColumnName+  &quot;)\n&quot;);
                        	strings.fkREsult.append(&quot; REFERENCES &quot;+fullTableName +&quot;(&quot;+ pKColumnName+  &quot;) \n&quot;);
                        	strings.fkREsult.append(&quot;     ON UPDATE NO ACTION\n&quot;);
                        	strings.fkREsult.append(&quot;     ON DELETE RESTRICT;\n&quot;);
                        }
                        exportedKeys.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }
                      //and INDEX
                        try{
	                        ResultSet indexInfo = dbMetaData.getIndexInfo(catalog, tableSchema, tableName, false, false);
//	                        TABLE_CAT String =&gt; table catalog (may be null) 
//	                        TABLE_SCHEM String =&gt; table schema (may be null) 
//	                        TABLE_NAME String =&gt; table name 
//	                        NON_UNIQUE boolean =&gt; Can index values be non-unique. false when TYPE is tableIndexStatistic 
//	                        INDEX_QUALIFIER String =&gt; index catalog (may be null); null when TYPE is tableIndexStatistic 
//	                        INDEX_NAME String =&gt; index name; null when TYPE is tableIndexStatistic 
//	                        TYPE short =&gt; index type: 
//	                        tableIndexStatistic - this identifies table statistics that are returned in conjuction with a table&#039;s index descriptions 
//	                        tableIndexClustered - this is a clustered index 
//	                        tableIndexHashed - this is a hashed index 
//	                        tableIndexOther - this is some other style of index 
//	                        ORDINAL_POSITION short =&gt; column sequence number within index; zero when TYPE is tableIndexStatistic 
//	                        COLUMN_NAME String =&gt; column name; null when TYPE is tableIndexStatistic 
//	                        ASC_OR_DESC String =&gt; column sort sequence, &quot;A&quot; =&gt; ascending, &quot;D&quot; =&gt; descending, may be null if sort sequence is not supported; null when TYPE is tableIndexStatistic 
//	                        CARDINALITY int =&gt; When TYPE is tableIndexStatistic, then this is the number of rows in the table; otherwise, it is the number of unique values in the index. 
//	                        PAGES int =&gt; When TYPE is tableIndexStatisic then this is the number of pages used for the table, otherwise it is the number of pages used for the current index. 
//	                        FILTER_CONDITION String =&gt; Filter condition, if any. (may be null) 
	                        
	                        //TODO if index unique and if something else than btree
	                        String indexComment = &quot;\n--index for  &quot;+fullTableName+&quot;\n&quot;;
	                        boolean hasIndex = false;
	                        String indexPreviousName = null;
	                        String columnNames=&quot;&quot;;
	                        StringBuilder tempIndexResult = new StringBuilder();
	                        
	                        while(indexInfo.next()){
	                        	String indexName = indexInfo.getString(&quot;INDEX_NAME&quot;);
	                        	if(!pkNames.contains(indexName)){
	                        		if(hasIndex == false){
	                        			tempIndexResult.append(indexComment);
	                        			hasIndex = true;
	                        		}
	                        		String columnName = indexInfo.getString(&quot;COLUMN_NAME&quot;);
	                        		
	                        		if(indexName.equals(indexPreviousName)){
	                        			tempIndexResult = new StringBuilder();
	                        			columnNames = columnNames+&quot;, &quot;+ columnName;
	                        			tempIndexResult.append(&quot; CREATE INDEX &quot;+indexName);
	                        			tempIndexResult.append(&quot;  ON &quot;+fullTableName);
	                        			tempIndexResult.append(&quot;  USING btree (&quot;+columnNames+&quot;) ; \n&quot;);
	                        			
	                        		}else{
	                        			strings.indexResult.append(&quot;&quot;+tempIndexResult);
	                        			
	                        			tempIndexResult = new StringBuilder();
			                        	columnNames = columnName;
			                        	tempIndexResult.append(&quot; CREATE INDEX &quot;+indexName);
			                        	tempIndexResult.append(&quot;  ON &quot;+fullTableName);
			                        	tempIndexResult.append(&quot;  USING btree (&quot;+columnName+&quot;) ; \n&quot;);
	                        		}
	                        		indexPreviousName = indexName;
	                        	}
	                        	
	                        }
	                        strings.indexResult.append(&quot;&quot;+tempIndexResult);
	                        
	                        indexInfo.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }
                        
                        try{
                        	//TODO doesnt work well because of unknown grants
	                        ResultSet grants = dbMetaData.getTablePrivileges(catalog, null, tableName);

//	                        TABLE_CAT String =&gt; table catalog (may be null) 
//	                        TABLE_SCHEM String =&gt; table schema (may be null) 
//	                        TABLE_NAME String =&gt; table name 
//	                        GRANTOR String =&gt; grantor of access (may be null) 
//	                        GRANTEE String =&gt; grantee of access 
//	                        PRIVILEGE String =&gt; name of access (SELECT, INSERT, UPDATE, REFRENCES, ...) 
//	                        IS_GRANTABLE String =&gt; &quot;YES&quot; if grantee is permitted to grant to others; &quot;NO&quot; if not; null if unknown 

	                        strings.grantResult.append(&quot;\n-- grants on &quot;+fullTableName+&quot;\n&quot;);
	                        while(grants.next()){
	                        	
	                        	String privileges = grants.getString(&quot;PRIVILEGE&quot;);

	                        	String grantee = grants.getString(&quot;GRANTEE&quot;);
	                        	
	                        	strings.grantResult.append(&quot; GRANT &quot;+privileges+ &quot; ON &quot;+fullTableName+ &quot; TO &quot;+grantee+ &quot;;\n&quot;);
	                        	
	                        }
	                        grants.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }
                        
                        // Right, we have a table, so we can go and dump it
                        dumpTable(dbConn, strings.insertResult, fullTableName);
                        
                    }
                    else if(&quot;VIEW&quot;.equalsIgnoreCase(tableType)){

                    	strings.viewResult.append(&quot;\nCREATE VIEW &quot;+fullTableName+&quot; \n(\n&quot;);
                    	strings.viewResult.append(&quot;&quot;);
                    	boolean firstLine = true;
                    	ResultSet tableMetaData = dbMetaData.getColumns(null, null, tableName, &quot;%&quot;);
                    	while(tableMetaData.next()){
                            if (firstLine) {
                                firstLine = false;
                            } else {
                                // If we&#039;re not the first line, then finish the previous line with a comma
                            	strings.viewResult.append(&quot;,\n&quot;);
                            }
                            String columnName = tableMetaData.getString(&quot;COLUMN_NAME&quot;);
                            strings.viewResult.append(&quot;   &quot;+columnName);
                    	}
                    	
                    	strings.viewResult.append(&quot;\n)\nAS\n &quot;);
                    	
                    	ResultSet executeQuery = dbConn.prepareCall(
                    			&quot; SELECT * FROM pg_views &quot; +
                    			&quot; WHERE viewname = &#039;&quot;+tableName+&quot;&#039;&quot;)
                    			.executeQuery();
                    	executeQuery.next();
                    	strings.viewResult.append(executeQuery.getString(&quot;definition&quot;));
                    	
                    }
                    
                } while (rs.next());
                rs.close();
            }
            //functions
            try{
            	//TODO if more than 3 arguments on function ... it fails.
            String functionDataString =
            &quot; SELECT r.* ,&quot;+
			&quot; (CASE WHEN pronargs = 0 THEN &#039;&#039; &quot;+
			&quot;       WHEN pronargs = 1 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) &quot;+
			&quot;       WHEN pronargs = 2 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) &#124;&#124; &#039;, &#039; &#124;&#124;(SELECT typname FROM pg_type WHERE oid = proargtypes [1]) &quot;+
			&quot;       WHEN pronargs = 3 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) &#124;&#124; &#039;, &#039; &#124;&#124;(SELECT typname FROM pg_type WHERE oid = proargtypes [1]) &#124;&#124; &#039;, &#039; &#124;&#124;(SELECT typname FROM pg_type WHERE oid = proargtypes [2])&quot;+ 
			&quot;       ELSE &#039;exception&#039; &quot;+
			&quot; 			  END) as args&quot;+
			&quot; FROM&quot;+
			&quot; (SELECT r.routine_schema sname, &quot;+
			&quot;    r.routine_name AS fname,&quot;+
			&quot;    r.security_type,&quot;+
			&quot;    r.routine_definition as data,&quot;+
			&quot;    r.external_language AS language,&quot;+
			&quot;    r.data_type AS return_type&quot;+
			&quot; FROM information_schema.routines r&quot;+
			&quot; WHERE r.specific_schema  &#039;information_schema&#039; AND r.specific_schema &#039;pg_catalog&#039;&quot;+
			&quot; ) as r, pg_proc p&quot;+
			&quot; WHERE  p.proname = r.fname&quot;;
            ResultSet functionColumns = dbConn.prepareCall(functionDataString)
        			.executeQuery();
            
            
            while(functionColumns.next()){
            	String funSchema = functionColumns.getString(&quot;sname&quot;);
            	String funName = functionColumns.getString(&quot;fname&quot;);
            	String args = functionColumns.getString(&quot;args&quot;);
            	String returnType = functionColumns.getString(&quot;return_type&quot;);
            	String security = functionColumns.getString(&quot;security_type&quot;);
            	String pllanguage = functionColumns.getString(&quot;language&quot;);
            	String fData = functionColumns.getString(&quot;data&quot;).replaceAll(&quot;&#039;&quot;, &quot;&#039;&#039;&quot;);
            	
            	strings.functionResult.append(&quot;CREATE OR REPLACE FUNCTION &quot;+funSchema+&quot;.&quot;+funName+&quot;(&quot;+args+&quot;) RETURNS &quot;+returnType+&quot;\n SECURITY &quot;+security+&quot; &quot; +
            			&quot; LANGUAGE &quot;+pllanguage+ &quot; AS &#039;&quot;+fData+&quot; &#039; ;\n&quot;);
            	
            }
            }catch(Exception e){
            	System.err.println(e);
            }
            
            //sequences
            try{
            	

            ResultSet sequences = dbConn.prepareCall(&quot;select sequence_name,sequence_schema from information_schema.sequences s &quot;)
        			.executeQuery();
            
            
            while(sequences.next()){
            	String sSchema = sequences.getString(&quot;sequence_schema&quot;);
            	String sName = sequences.getString(&quot;sequence_name&quot;);
            	
            	ResultSet query = dbConn.prepareCall(&quot;select start_value, increment_by from &quot;+sSchema+&quot;.&quot;+sName).executeQuery();
            	query.next();
            	String startValue = query.getString(&quot;start_value&quot;);
            	String incrementBy = query.getString(&quot;increment_by&quot;);
            	
            	
            	strings.sequenceResult.append(&quot;\nCREATE SEQUENCE &quot;+sSchema+&quot;.&quot;+sName+&quot; \n&quot;);
            	strings.sequenceResult.append(&quot;START WITH &quot;+startValue+&quot; INCREMENT by &quot;+incrementBy+&quot;; \n&quot;);
            	
            }
            }catch(Exception e){
            	System.err.println(e);
            }
            
            dbConn.close();
            
            for(String s :schemas){
            	strings.schemaResult.append(&quot;CREATE SCHEMA &quot;+s+&quot;;\n&quot;);
            }

            return strings;
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use Options &#124; File Templates.
        }
        return null;
    }

	/** dump this particular table to the string buffer */
    private static void dumpTable(Connection dbConn, StringBuilder result, String tableName) {
        try {
            // First we output the create table stuff
            PreparedStatement stmt = dbConn.prepareStatement(&quot;SELECT * FROM &quot;+tableName);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            // Now we can output the actual data
            result.append(&quot;\n\n-- Data for &quot;+tableName+&quot;\n&quot;);
            while (rs.next()) {
                result.append(&quot;INSERT INTO &quot;+tableName+&quot; VALUES (&quot;);
                for (int i=0; i 0) {
                        result.append(&quot;, &quot;);
                    }
                    Object value = rs.getObject(i+1);
                    if (value == null) {
                        result.append(&quot;NULL&quot;);
                    } else {
                        String outputValue = value.toString();
                        outputValue = outputValue.replaceAll(&quot;&#039;&quot;,&quot;\\&#039;&quot;);
                        result.append(&quot;&#039;&quot;+outputValue+&quot;&#039;&quot;);
                    }
                }
                result.append(&quot;);\n&quot;);
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            System.err.println(&quot;Unable to dump table &quot;+tableName+&quot; because: &quot;+e);
        }
    }

    /** Main method takes arguments for connection to JDBC etc. */
    public static void main(String[] args) {

        if (args.length != 1) {
           System.err.println(&quot;usage: db2sql &quot;);
        }
        // Right so there&#039;s one argument, we assume it&#039;s a property file
        // so lets open it
        Properties props = new Properties();
        try {
            props.load(new FileInputStream(args[0]));

            Strings strings = dumpDB(props);
            
            try{
			
			System.out.println(strings.schemaResult.toString());
			System.out.println(strings.initResult.toString());
			System.out.println(strings.functionResult.toString());
			System.out.println(strings.viewResult.toString());
			System.out.println(strings.insertResult.toString());
			System.out.println(strings.indexResult.toString());
			System.out.println(strings.fkREsult.toString());
			System.out.println(strings.sequenceResult.toString());
			/*
            	  
            	  FileWriter fstream = new FileWriter(&quot;dump_database.txt&quot;);
            	  BufferedWriter out = new BufferedWriter(fstream);
            	  out.write(strings.schemaResult.toString());
            	  out.write(strings.initResult.toString());
            	  out.write(strings.functionResult.toString());
            	  out.write(strings.viewResult.toString());
            	  out.write(strings.insertResult.toString());
            	  out.write(strings.indexResult.toString());
            	  out.write(strings.fkREsult.toString());
            	  out.write(strings.sequenceResult.toString());
            	  //Close the output stream
            	  out.close();
            	  }catch (Exception e){//Catch exception if any
            	  System.err.println(&quot;Error: &quot; + e.getMessage());
            	  }
            */
            
        } catch (IOException e) {
            System.err.println(&quot;Unable to open property file: &quot;+args[0]+&quot; exception: &quot;+e);
        }

    }
}
class Strings{
	StringBuilder schemaResult = new StringBuilder();
	StringBuilder initResult = new StringBuilder();
	StringBuilder functionResult = new StringBuilder();
	StringBuilder viewResult = new StringBuilder();
	StringBuilder fkREsult = new StringBuilder();
	StringBuilder indexResult = new StringBuilder();
	StringBuilder insertResult = new StringBuilder();
	StringBuilder grantResult = new StringBuilder();
	StringBuilder sequenceResult = new StringBuilder();
	
}
&lt;/pre&gt;</description>
		<content:encoded><![CDATA[<p>i made much more superious version of this algorithm.</p>
<p>Works only for postgres</p>
<p>generates tables,sequences, functions,indexes, fk, views, schemas, db dump</p>
<p>code:</p>
<pre>
/**
 * Copyright Isocra Ltd 2004
 * You can use, modify and freely distribute this file as long as you credit Isocra Ltd.
 * There is no explicit or implied guarantee of functionality associated with this file, use it at your own risk.
 */

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * This class connects to a database and dumps all the tables and contents out to stdout in the form of
 * a set of SQL executable statements
 */
public class db2sql {

    /** Dump the whole database to an SQL string */
    public static Strings dumpDB(Properties props) {
        String driverClassName = props.getProperty("driver.class");
        String driverURL = props.getProperty("driver.url");
        // Default to not having a quote character
        String columnNameQuote = props.getProperty("columnName.quoteChar", "");
        DatabaseMetaData dbMetaData = null;
        Connection dbConn = null;
        try {
            Class.forName(driverClassName);
            dbConn = DriverManager.getConnection(driverURL, props);
            dbMetaData = dbConn.getMetaData();
        }
        catch( Exception e ) {
            System.err.println("Unable to connect to database: "+e);
            return null;
        }
        try {
        	Strings strings = new Strings();
            Set schemas = new HashSet();
            String catalog = props.getProperty("catalog");
            String schema = props.getProperty("schemaPattern");
            String tables = props.getProperty("tableName");
            String[] types = {"VIEW","TABLE"};
            ResultSet rs = dbMetaData.getTables(catalog, schema, tables, types);
            if (! rs.next()) {
                System.err.println("Unable to find any tables matching: catalog="+catalog+" schema="+schema+" tables="+tables);
                rs.close();
            } else {
                // Right, we have some tables, so we can go to work.
                // the details we have are
                // TABLE_CAT String =&gt; table catalog (may be null)
                // TABLE_SCHEM String =&gt; table schema (may be null)
                // TABLE_NAME String =&gt; table name
                // TABLE_TYPE String =&gt; table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
                // REMARKS String =&gt; explanatory comment on the table
                // TYPE_CAT String =&gt; the types catalog (may be null)
                // TYPE_SCHEM String =&gt; the types schema (may be null)
                // TYPE_NAME String =&gt; type name (may be null)
                // SELF_REFERENCING_COL_NAME String =&gt; name of the designated "identifier" column of a typed table (may be null)
                // REF_GENERATION String =&gt; specifies how values in SELF_REFERENCING_COL_NAME are created. Values are "SYSTEM", "USER", "DERIVED". (may be null)
                // We will ignore the schema and stuff, because people might want to import it somewhere else
                // We will also ignore any tables that aren't of type TABLE for now.
                // We use a do-while because we've already caled rs.next to see if there are any rows
                do {
                    String tableName = rs.getString("TABLE_NAME");
                    String tableType = rs.getString("TABLE_TYPE");
                    String tableSchema = rs.getString("TABLE_SCHEM");
                    String fullTableName = tableSchema+"."+tableName;
                    schemas.add(tableSchema);
                    if ("TABLE".equalsIgnoreCase(tableType)) {
                    	strings.initResult.append("\n\n-- "+fullTableName);
                    	strings.initResult.append("\nCREATE TABLE "+fullTableName+" (\n");
                        ResultSet tableMetaData = dbMetaData.getColumns(null, null, tableName, "%");
                        boolean firstLine = true;
                        while (tableMetaData.next()) {
                            if (firstLine) {
                                firstLine = false;
                            } else {
                                // If we're not the first line, then finish the previous line with a comma
                            	strings.initResult.append(",\n");
                            }
                            String columnName = tableMetaData.getString("COLUMN_NAME");
                            String columnType = tableMetaData.getString("TYPE_NAME");
                            // WARNING: this may give daft answers for some types on some databases (eg JDBC-ODBC link)
                            String decimalDigits = tableMetaData.getString("DECIMAL_DIGITS");
                            String columnSize = tableMetaData.getString("COLUMN_SIZE");
                            String columnPrecision;

                            if(columnType.equals("varchar") ){
                            	columnPrecision = " ("+columnSize+")";
                            }else if(columnType.equals("numeric") || columnType.equals("decimal")){
                            	if(Integer.parseInt(columnSize) &gt;1000)
                            		columnSize="1000";
                            	columnPrecision=" ("+columnSize+", "+decimalDigits+" )";

                            }else
                            	columnPrecision = "";

                            String nullable = tableMetaData.getString("IS_NULLABLE");
                            String defaultValue = tableMetaData.getString("COLUMN_DEF");
                            if(defaultValue == null)
                            	defaultValue ="";
                            else
                            	defaultValue =" DEFAULT "+defaultValue;

                            if(columnType.equalsIgnoreCase("SERIAL")){
                            	defaultValue="";
                            	columnSize="";
                            }
                            String nullString = "NULL";
                            if ("NO".equalsIgnoreCase(nullable)) {
                                nullString = "NOT NULL";
                            }
                            strings.initResult.append("    "+columnNameQuote+columnName+columnNameQuote+" "+columnType+columnPrecision+""+" "+nullString+ defaultValue);
                        }
                        tableMetaData.close();

                        // Now we need to put the primary key constraint
                        Set pkNames = new HashSet();
                        try {
                            ResultSet primaryKeys = dbMetaData.getPrimaryKeys(catalog, schema, tableName);
                            // What we might get:
                            // TABLE_CAT String =&gt; table catalog (may be null)
                            // TABLE_SCHEM String =&gt; table schema (may be null)
                            // TABLE_NAME String =&gt; table name
                            // COLUMN_NAME String =&gt; column name
                            // KEY_SEQ short =&gt; sequence number within primary key
                            // PK_NAME String =&gt; primary key name (may be null)
                            String primaryKeyName = null;
                            StringBuffer primaryKeyColumns = new StringBuffer();
                            while (primaryKeys.next()) {
                                String thisKeyName = primaryKeys.getString("PK_NAME");
                                pkNames.add(thisKeyName);
                                if ((thisKeyName != null &amp;&amp; primaryKeyName == null)
                                        || (thisKeyName == null &amp;&amp; primaryKeyName != null)
                                        || (thisKeyName != null &amp;&amp; ! thisKeyName.equals(primaryKeyName))
                                        || (primaryKeyName != null &amp;&amp; ! primaryKeyName.equals(thisKeyName))) {
                                    // the keynames aren't the same, so output all that we have so far (if anything)
                                    // and start a new primary key entry
                                    if (primaryKeyColumns.length() &gt; 0) {
                                        // There's something to output
                                    	strings.initResult.append(",\n CONSTRAINT "+primaryKeyName+" PRIMARY KEY ");

                                    	strings.initResult.append("("+primaryKeyColumns.toString()+")");
                                    }
                                    // Start again with the new name
                                    primaryKeyColumns = new StringBuffer();
                                    primaryKeyName = thisKeyName;
                                }
                                // Now append the column
                                if (primaryKeyColumns.length() &gt; 0) {
                                    primaryKeyColumns.append(", ");
                                }
                                primaryKeyColumns.append(primaryKeys.getString("COLUMN_NAME"));
                            }
                            if (primaryKeyColumns.length() &gt; 0) {
                                // There's something to output
                            	strings.initResult.append(",\n    CONSTRAINT "+primaryKeyName+" PRIMARY KEY ");
                            	strings.initResult.append(" ("+primaryKeyColumns.toString()+")");
                            }
                        } catch (SQLException e) {
                            // NB you will get this exception with the JDBC-ODBC link because it says
                            // [Microsoft][ODBC Driver Manager] Driver does not support this function
                            System.err.println("Unable to get primary keys for table "+tableName+" because "+e);
                        }
                        strings.initResult.append("\n);\n");
                        //and FK
                        try{
                        	ResultSet exportedKeys = dbMetaData.getExportedKeys(catalog, tableSchema, tableName);

//                        	PKTABLE_CAT String =&gt; primary key table catalog (may be null)
//                        	PKTABLE_SCHEM String =&gt; primary key table schema (may be null)
//                        	PKTABLE_NAME String =&gt; primary key table name
//                        	PKCOLUMN_NAME String =&gt; primary key column name
//                        	FKTABLE_CAT String =&gt; foreign key table catalog (may be null) being exported (may be null)
//                        	FKTABLE_SCHEM String =&gt; foreign key table schema (may be null) being exported (may be null)
//                        	FKTABLE_NAME String =&gt; foreign key table name being exported
//                        	FKCOLUMN_NAME String =&gt; foreign key column name being exported
//                        	KEY_SEQ short =&gt; sequence number within foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
//                        	UPDATE_RULE short =&gt; What happens to foreign key when primary is updated:
//                        	importedNoAction - do not allow update of primary key if it has been imported
//                        	importedKeyCascade - change imported key to agree with primary key update
//                        	importedKeySetNull - change imported key to NULL if its primary key has been updated
//                        	importedKeySetDefault - change imported key to default values if its primary key has been updated
//                        	importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
//                        	DELETE_RULE short =&gt; What happens to the foreign key when primary is deleted.
//                        	importedKeyNoAction - do not allow delete of primary key if it has been imported
//                        	importedKeyCascade - delete rows that import a deleted key
//                        	importedKeySetNull - change imported key to NULL if its primary key has been deleted
//                        	importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
//                        	importedKeySetDefault - change imported key to default if its primary key has been deleted
//                        	FK_NAME String =&gt; foreign key name (may be null)
//                        	PK_NAME String =&gt; primary key name (may be null)
//                        	DEFERRABILITY short =&gt; can the evaluation of foreign key constraints be deferred until commit
//                        	importedKeyInitiallyDeferred - see SQL92 for definition
//                        	importedKeyInitiallyImmediate - see SQL92 for definition
//                        	importedKeyNotDeferrable - see SQL92 for definition 

                        while(exportedKeys.next()){
                        	String fkName = exportedKeys.getString("FK_NAME");
                        	String fKColumnName = exportedKeys.getString("FKCOLUMN_NAME");
                        	String pKColumnName = exportedKeys.getString("PKCOLUMN_NAME");
                        	String fKTableFullName = exportedKeys.getString("FKTABLE_SCHEM")+"."+exportedKeys.getString("FKTABLE_NAME");

                        	strings.fkREsult.append("\n--fk for "+fKTableFullName+"\n");
                        	strings.fkREsult.append("\nALTER TABLE "+fKTableFullName+"\n");
                        	strings.fkREsult.append(" ADD CONSTRAINT "+fkName + " FOREIGN KEY ("+ fKColumnName+  ")\n");
                        	strings.fkREsult.append(" REFERENCES "+fullTableName +"("+ pKColumnName+  ") \n");
                        	strings.fkREsult.append("     ON UPDATE NO ACTION\n");
                        	strings.fkREsult.append("     ON DELETE RESTRICT;\n");
                        }
                        exportedKeys.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }
                      //and INDEX
                        try{
	                        ResultSet indexInfo = dbMetaData.getIndexInfo(catalog, tableSchema, tableName, false, false);
//	                        TABLE_CAT String =&gt; table catalog (may be null)
//	                        TABLE_SCHEM String =&gt; table schema (may be null)
//	                        TABLE_NAME String =&gt; table name
//	                        NON_UNIQUE boolean =&gt; Can index values be non-unique. false when TYPE is tableIndexStatistic
//	                        INDEX_QUALIFIER String =&gt; index catalog (may be null); null when TYPE is tableIndexStatistic
//	                        INDEX_NAME String =&gt; index name; null when TYPE is tableIndexStatistic
//	                        TYPE short =&gt; index type:
//	                        tableIndexStatistic - this identifies table statistics that are returned in conjuction with a table's index descriptions
//	                        tableIndexClustered - this is a clustered index
//	                        tableIndexHashed - this is a hashed index
//	                        tableIndexOther - this is some other style of index
//	                        ORDINAL_POSITION short =&gt; column sequence number within index; zero when TYPE is tableIndexStatistic
//	                        COLUMN_NAME String =&gt; column name; null when TYPE is tableIndexStatistic
//	                        ASC_OR_DESC String =&gt; column sort sequence, "A" =&gt; ascending, "D" =&gt; descending, may be null if sort sequence is not supported; null when TYPE is tableIndexStatistic
//	                        CARDINALITY int =&gt; When TYPE is tableIndexStatistic, then this is the number of rows in the table; otherwise, it is the number of unique values in the index.
//	                        PAGES int =&gt; When TYPE is tableIndexStatisic then this is the number of pages used for the table, otherwise it is the number of pages used for the current index.
//	                        FILTER_CONDITION String =&gt; Filter condition, if any. (may be null) 

	                        //TODO if index unique and if something else than btree
	                        String indexComment = "\n--index for  "+fullTableName+"\n";
	                        boolean hasIndex = false;
	                        String indexPreviousName = null;
	                        String columnNames="";
	                        StringBuilder tempIndexResult = new StringBuilder();

	                        while(indexInfo.next()){
	                        	String indexName = indexInfo.getString("INDEX_NAME");
	                        	if(!pkNames.contains(indexName)){
	                        		if(hasIndex == false){
	                        			tempIndexResult.append(indexComment);
	                        			hasIndex = true;
	                        		}
	                        		String columnName = indexInfo.getString("COLUMN_NAME");

	                        		if(indexName.equals(indexPreviousName)){
	                        			tempIndexResult = new StringBuilder();
	                        			columnNames = columnNames+", "+ columnName;
	                        			tempIndexResult.append(" CREATE INDEX "+indexName);
	                        			tempIndexResult.append("  ON "+fullTableName);
	                        			tempIndexResult.append("  USING btree ("+columnNames+") ; \n");

	                        		}else{
	                        			strings.indexResult.append(""+tempIndexResult);

	                        			tempIndexResult = new StringBuilder();
			                        	columnNames = columnName;
			                        	tempIndexResult.append(" CREATE INDEX "+indexName);
			                        	tempIndexResult.append("  ON "+fullTableName);
			                        	tempIndexResult.append("  USING btree ("+columnName+") ; \n");
	                        		}
	                        		indexPreviousName = indexName;
	                        	}

	                        }
	                        strings.indexResult.append(""+tempIndexResult);

	                        indexInfo.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }

                        try{
                        	//TODO doesnt work well because of unknown grants
	                        ResultSet grants = dbMetaData.getTablePrivileges(catalog, null, tableName);

//	                        TABLE_CAT String =&gt; table catalog (may be null)
//	                        TABLE_SCHEM String =&gt; table schema (may be null)
//	                        TABLE_NAME String =&gt; table name
//	                        GRANTOR String =&gt; grantor of access (may be null)
//	                        GRANTEE String =&gt; grantee of access
//	                        PRIVILEGE String =&gt; name of access (SELECT, INSERT, UPDATE, REFRENCES, ...)
//	                        IS_GRANTABLE String =&gt; "YES" if grantee is permitted to grant to others; "NO" if not; null if unknown 

	                        strings.grantResult.append("\n-- grants on "+fullTableName+"\n");
	                        while(grants.next()){

	                        	String privileges = grants.getString("PRIVILEGE");

	                        	String grantee = grants.getString("GRANTEE");

	                        	strings.grantResult.append(" GRANT "+privileges+ " ON "+fullTableName+ " TO "+grantee+ ";\n");

	                        }
	                        grants.close();
                        }catch(Exception e){
                        	System.out.println(e);
                        }

                        // Right, we have a table, so we can go and dump it
                        dumpTable(dbConn, strings.insertResult, fullTableName);

                    }
                    else if("VIEW".equalsIgnoreCase(tableType)){

                    	strings.viewResult.append("\nCREATE VIEW "+fullTableName+" \n(\n");
                    	strings.viewResult.append("");
                    	boolean firstLine = true;
                    	ResultSet tableMetaData = dbMetaData.getColumns(null, null, tableName, "%");
                    	while(tableMetaData.next()){
                            if (firstLine) {
                                firstLine = false;
                            } else {
                                // If we're not the first line, then finish the previous line with a comma
                            	strings.viewResult.append(",\n");
                            }
                            String columnName = tableMetaData.getString("COLUMN_NAME");
                            strings.viewResult.append("   "+columnName);
                    	}

                    	strings.viewResult.append("\n)\nAS\n ");

                    	ResultSet executeQuery = dbConn.prepareCall(
                    			" SELECT * FROM pg_views " +
                    			" WHERE viewname = '"+tableName+"'")
                    			.executeQuery();
                    	executeQuery.next();
                    	strings.viewResult.append(executeQuery.getString("definition"));

                    }

                } while (rs.next());
                rs.close();
            }
            //functions
            try{
            	//TODO if more than 3 arguments on function ... it fails.
            String functionDataString =
            " SELECT r.* ,"+
			" (CASE WHEN pronargs = 0 THEN '' "+
			"       WHEN pronargs = 1 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) "+
			"       WHEN pronargs = 2 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) || ', ' ||(SELECT typname FROM pg_type WHERE oid = proargtypes [1]) "+
			"       WHEN pronargs = 3 THEN (SELECT typname FROM pg_type WHERE oid = proargtypes [0]) || ', ' ||(SELECT typname FROM pg_type WHERE oid = proargtypes [1]) || ', ' ||(SELECT typname FROM pg_type WHERE oid = proargtypes [2])"+
			"       ELSE 'exception' "+
			" 			  END) as args"+
			" FROM"+
			" (SELECT r.routine_schema sname, "+
			"    r.routine_name AS fname,"+
			"    r.security_type,"+
			"    r.routine_definition as data,"+
			"    r.external_language AS language,"+
			"    r.data_type AS return_type"+
			" FROM information_schema.routines r"+
			" WHERE r.specific_schema  'information_schema' AND r.specific_schema 'pg_catalog'"+
			" ) as r, pg_proc p"+
			" WHERE  p.proname = r.fname";
            ResultSet functionColumns = dbConn.prepareCall(functionDataString)
        			.executeQuery();

            while(functionColumns.next()){
            	String funSchema = functionColumns.getString("sname");
            	String funName = functionColumns.getString("fname");
            	String args = functionColumns.getString("args");
            	String returnType = functionColumns.getString("return_type");
            	String security = functionColumns.getString("security_type");
            	String pllanguage = functionColumns.getString("language");
            	String fData = functionColumns.getString("data").replaceAll("'", "''");

            	strings.functionResult.append("CREATE OR REPLACE FUNCTION "+funSchema+"."+funName+"("+args+") RETURNS "+returnType+"\n SECURITY "+security+" " +
            			" LANGUAGE "+pllanguage+ " AS '"+fData+" ' ;\n");

            }
            }catch(Exception e){
            	System.err.println(e);
            }

            //sequences
            try{

            ResultSet sequences = dbConn.prepareCall("select sequence_name,sequence_schema from information_schema.sequences s ")
        			.executeQuery();

            while(sequences.next()){
            	String sSchema = sequences.getString("sequence_schema");
            	String sName = sequences.getString("sequence_name");

            	ResultSet query = dbConn.prepareCall("select start_value, increment_by from "+sSchema+"."+sName).executeQuery();
            	query.next();
            	String startValue = query.getString("start_value");
            	String incrementBy = query.getString("increment_by");

            	strings.sequenceResult.append("\nCREATE SEQUENCE "+sSchema+"."+sName+" \n");
            	strings.sequenceResult.append("START WITH "+startValue+" INCREMENT by "+incrementBy+"; \n");

            }
            }catch(Exception e){
            	System.err.println(e);
            }

            dbConn.close();

            for(String s :schemas){
            	strings.schemaResult.append("CREATE SCHEMA "+s+";\n");
            }

            return strings;
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }
        return null;
    }

	/** dump this particular table to the string buffer */
    private static void dumpTable(Connection dbConn, StringBuilder result, String tableName) {
        try {
            // First we output the create table stuff
            PreparedStatement stmt = dbConn.prepareStatement("SELECT * FROM "+tableName);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            // Now we can output the actual data
            result.append("\n\n-- Data for "+tableName+"\n");
            while (rs.next()) {
                result.append("INSERT INTO "+tableName+" VALUES (");
                for (int i=0; i 0) {
                        result.append(", ");
                    }
                    Object value = rs.getObject(i+1);
                    if (value == null) {
                        result.append("NULL");
                    } else {
                        String outputValue = value.toString();
                        outputValue = outputValue.replaceAll("'","\\'");
                        result.append("'"+outputValue+"'");
                    }
                }
                result.append(");\n");
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            System.err.println("Unable to dump table "+tableName+" because: "+e);
        }
    }

    /** Main method takes arguments for connection to JDBC etc. */
    public static void main(String[] args) {

        if (args.length != 1) {
           System.err.println("usage: db2sql ");
        }
        // Right so there's one argument, we assume it's a property file
        // so lets open it
        Properties props = new Properties();
        try {
            props.load(new FileInputStream(args[0]));

            Strings strings = dumpDB(props);

            try{

			System.out.println(strings.schemaResult.toString());
			System.out.println(strings.initResult.toString());
			System.out.println(strings.functionResult.toString());
			System.out.println(strings.viewResult.toString());
			System.out.println(strings.insertResult.toString());
			System.out.println(strings.indexResult.toString());
			System.out.println(strings.fkREsult.toString());
			System.out.println(strings.sequenceResult.toString());
			/*

            	  FileWriter fstream = new FileWriter("dump_database.txt");
            	  BufferedWriter out = new BufferedWriter(fstream);
            	  out.write(strings.schemaResult.toString());
            	  out.write(strings.initResult.toString());
            	  out.write(strings.functionResult.toString());
            	  out.write(strings.viewResult.toString());
            	  out.write(strings.insertResult.toString());
            	  out.write(strings.indexResult.toString());
            	  out.write(strings.fkREsult.toString());
            	  out.write(strings.sequenceResult.toString());
            	  //Close the output stream
            	  out.close();
            	  }catch (Exception e){//Catch exception if any
            	  System.err.println("Error: " + e.getMessage());
            	  }
            */

        } catch (IOException e) {
            System.err.println("Unable to open property file: "+args[0]+" exception: "+e);
        }

    }
}
class Strings{
	StringBuilder schemaResult = new StringBuilder();
	StringBuilder initResult = new StringBuilder();
	StringBuilder functionResult = new StringBuilder();
	StringBuilder viewResult = new StringBuilder();
	StringBuilder fkREsult = new StringBuilder();
	StringBuilder indexResult = new StringBuilder();
	StringBuilder insertResult = new StringBuilder();
	StringBuilder grantResult = new StringBuilder();
	StringBuilder sequenceResult = new StringBuilder();

}
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: cisco.nosle.com</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1343</link>
		<dc:creator>cisco.nosle.com</dc:creator>
		<pubDate>Sat, 12 Feb 2011 18:27:15 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1343</guid>
		<description>Denis: From some of the comments here, I think it would be better if you showed where to load the property file including the load syntax. In any case it is a cool program. Thx.</description>
		<content:encoded><![CDATA[<p>Denis: From some of the comments here, I think it would be better if you showed where to load the property file including the load syntax. In any case it is a cool program. Thx.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1211</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Wed, 01 Sep 2010 07:31:51 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1211</guid>
		<description>once i try to execute your code i get this error: 
usage: db2sql 
Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: 0
        at dbtosql.db2sql.main(db2sql.java:202)

Please help on what i must do</description>
		<content:encoded><![CDATA[<p>once i try to execute your code i get this error:<br />
usage: db2sql<br />
Exception in thread &#8220;main&#8221; java.lang.ArrayIndexOutOfBoundsException: 0<br />
        at dbtosql.db2sql.main(db2sql.java:202)</p>
<p>Please help on what i must do</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1210</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Wed, 01 Sep 2010 06:51:37 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1210</guid>
		<description>How to pass the propeties file as a parameter in the program?</description>
		<content:encoded><![CDATA[<p>How to pass the propeties file as a parameter in the program?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1209</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Wed, 01 Sep 2010 06:36:57 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1209</guid>
		<description>which line in the code where i have to call the properties file in your code?</description>
		<content:encoded><![CDATA[<p>which line in the code where i have to call the properties file in your code?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1208</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Wed, 01 Sep 2010 06:31:49 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1208</guid>
		<description>which line in the code where i call the properties file?</description>
		<content:encoded><![CDATA[<p>which line in the code where i call the properties file?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: DenisH</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1207</link>
		<dc:creator>DenisH</dc:creator>
		<pubDate>Wed, 01 Sep 2010 06:13:08 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1207</guid>
		<description>Hi Xolani,

You do need the properties file (unless you want to hard-code the values in to the Java). You can call the properties file (a simple text file) whatever you like and then pass it as a parameter to the program when you run it.</description>
		<content:encoded><![CDATA[<p>Hi Xolani,</p>
<p>You do need the properties file (unless you want to hard-code the values in to the Java). You can call the properties file (a simple text file) whatever you like and then pass it as a parameter to the program when you run it.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1206</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Tue, 31 Aug 2010 13:18:18 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1206</guid>
		<description>how to save properties file? which name should i put before the .properties?</description>
		<content:encoded><![CDATA[<p>how to save properties file? which name should i put before the .properties?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Xolani</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1205</link>
		<dc:creator>Xolani</dc:creator>
		<pubDate>Tue, 31 Aug 2010 13:16:30 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1205</guid>
		<description>hi denish

is it possible to run your code: http://www.isocra.com/articles/db2sql.java without using the properties file?
i want to copy the database, tables, and its data and convert it to mysql</description>
		<content:encoded><![CDATA[<p>hi denish</p>
<p>is it possible to run your code: <a href="http://www.isocra.com/articles/db2sql.java" rel="nofollow">http://www.isocra.com/articles/db2sql.java</a> without using the properties file?<br />
i want to copy the database, tables, and its data and convert it to mysql</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: GuEsT</title>
		<link>http://www.isocra.com/2004/10/dumptosql/comment-page-1/#comment-1092</link>
		<dc:creator>GuEsT</dc:creator>
		<pubDate>Tue, 20 Apr 2010 03:43:02 +0000</pubDate>
		<guid isPermaLink="false">http://www.isocra.com/new/2004/10/dumptosql/#comment-1092</guid>
		<description>Oh sorry.. My bad.. its has to be DenisH.. Not dinesh... Sorry guys.. DenisH, thank you for the program... :) 

PS:
Sorry the name mix up... :(</description>
		<content:encoded><![CDATA[<p>Oh sorry.. My bad.. its has to be DenisH.. Not dinesh&#8230; Sorry guys.. DenisH, thank you for the program&#8230; <img src='http://www.isocra.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>PS:<br />
Sorry the name mix up&#8230; <img src='http://www.isocra.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
]]></content:encoded>
	</item>
</channel>
</rss>

