Get SQL Create Table DDL Statement using JDBC
Get SQL Create Table DDL Statement using JDBC.
Javadoc available at https://www.javatapas.com/docs/javatapas/sql/GetSqlCreateTableStatement.html
public static String getSqlCreateTableStatement(Connection conn, String tableName) throws SQLException {
StringBuilder sql = new StringBuilder();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM " + tableName + " WHERE 0 = 1");
ResultSetMetaData rsmd = rset.getMetaData();
sql.append("CREATE TABLE " + tableName + " (");
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String nullable = "";
int x = rsmd.isNullable(i);
if (x == ResultSetMetaData.columnNoNulls){nullable = "NOT NULL";}
else {nullable = "NULL";}
String colType = "";
if (rsmd.getColumnType(i) == Types.BIGINT ||
rsmd.getColumnType(i) == Types.DECIMAL ||
rsmd.getColumnType(i) == Types.DOUBLE ||
rsmd.getColumnType(i) == Types.FLOAT ||
rsmd.getColumnType(i) == Types.INTEGER ||
rsmd.getColumnType(i) == Types.NUMERIC ||
rsmd.getColumnType(i) == Types.SMALLINT){colType = rsmd.getColumnTypeName(i) + "(" + rsmd.getPrecision(i) + "," + rsmd.getScale(i) + ")";}
else if (rsmd.getColumnType(i) == Types.VARCHAR ||
rsmd.getColumnType(i) == Types.CHAR){colType = rsmd.getColumnTypeName(i) + "(" + rsmd.getPrecision(i) + ")";}
else {colType = rsmd.getColumnTypeName(i);}
String eol = (i == rsmd.getColumnCount()) ? "" : ",";
sql.append(rsmd.getColumnName(i) + " " + colType + " " + nullable + eol);
}
sql.append(")");
rset.close();
stmt.close();
return sql.toString();
}