Using JDBC to Connect to MySQL Part 2

In part 1 of this series, we discovered how to setup a database connection and execute statements that do not return any data. Here we will handle those types of queries and the data we get from them.

If you are expecting data back from your query, you need another data type, the ResultSet. It is the object that gets the data from the query and reformats it to give back to your program. It is created from the Statement object.

stat.executeQuery("SELECT id, name, status FROM writers");
ResultSet result = stat.getResultSet();

Notice I am using the same statement object as before, not a new one. One statement object can be used to make multiple queries with the same database connection before it is closed. This is helpful when you need to make several queries back-to-back.

while (result.next())
{
	int id = result.getInt("id");
	String name = result.getString("name");
	String status = result.getString("status");
	System.out.println
  ("id = " + id + ", name = " + name + ", status = " + status);
}
result.close();

There are different methods for getting different data types from the ResultSet object. getInt() and getString() are just two of the more commonly used. These are shown using the column names as arguments to get the values from result, but you can also get them like this.

	int id = result.getInt(1);
	String name = result.getString(2);
	String name = result.getString(3);

Notice that the indeces begin counting at 1, instead of 0 like an array would.

Part 3 of this series goes even further into database integration with more advanced techniques for writing queries.

Bryan Young
About Bryan Young
Bryan Young is a staff writer for WebProNews.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>