Never been to DZone Snippets before?

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

About this user

Mike Wilson www.whisperingwind.co.uk

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Open a JDBC connection

This opens a JDBC connection givine a driver class name, database URL, user name and password. It is possible this method is deprecated and some newer procedure is preferred. I need to look into that.

    /*
    ** driverClass is the JDBC driver class name as a String.
    */

    try
    {
	Class.forName (driverClass);
	connection = DriverManager.getConnection (url,
	    userName, password);
	connection.setAutoCommit (false);
    }
    catch (SQLException ex)
    {
	/*
	** "Connect error"...
	*/
    }
    catch (java.lang.ClassNotFoundException ex)
    {
	/*
	** "Driver error"...
	*/
    }

Execute arbitary SQL in JDBC & get column names etc from the meta data

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 ();
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS