DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Execute Arbitary SQL In JDBC & Get Column Names Etc From The Meta Data

05.14.2006
| 9041 views |
  • submit to reddit
        This will execute an arbitary SQL string in JDBC and extract the column names. I extracted this code from a much larger module I wrote years ago, so it isn't complete and hasn't been tested. You have been warned.

    /*
    ** connection is a java.sql.Connection obtained in the usual way.
    */

    PreparedStatement statement =
	connection.prepareStatement (sqlString);
    statement.setMaxRows (configModel.getMaxRows ());

    if (statement.execute ())
    {
	ResultSet resultSet = statement.getResultSet ();
	ResultSetMetaData metaData = resultSet.getMetaData ();

	/*
	** Get the column names.
	*/

	for (int i = 0 ; i < metaData.getColumnCount () ; i++)
	{
	    int columnType = metaData.getColumnType (i + 1);
	    String columnName = metaData.getColumnLabel (i + 1);

	    /*
	    ** Do something with columnType & columnName.
	    */

	}

	/*
	** Fetch the rows.
	*/

	while (resultSet.next ())
	{
	    String value;

	    for (int i = 0 ; i < metaData.getColumnCount () ; i++)
		value = resultSet.getString (i + 1);
	}
    }
    else
    {
	/*
	** Query was probably update/insert/delete.
	*/

	int rowCount = statement.getUpdateCount ();
    }

    statement.close ();