13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

334Chapter 15Accessing the Data: An Introducti<strong>on</strong> to JDBCIf this all seems rather simplistic, well, it is. It may not be a very sophisticatedway of blending SQL with Java, but it is very effective. Notice that youd<strong>on</strong>’t get any syntax checking <strong>on</strong> the SQL query when you write your program,though it will throw an excepti<strong>on</strong> at runtime if you try to execute ungrammaticalSQL. For this reas<strong>on</strong> it is not uncomm<strong>on</strong> to try out all your SQL beforehand,cutting and pasting the queries out of the SQL program that you use fordirectly talking with your database. Some developers even like to keep theirqueries in files, to be read at runtime. This has the added flexibility (and risk)of being able to change the query without recompiling the code. Since the recompiledoesn’t provide any syntax checking <strong>on</strong> your query string anyway, itseems a reas<strong>on</strong>able way to go, provided that you properly write-protect the filesc<strong>on</strong>taining the queries.15.5GETTING RESULTSReturning to our example, we see that we can execute the query <strong>on</strong> theStatement object and then get out the results:ResultSet rs = stmt.executeQuery();// read the resultswhile(rs.next()) {int id = rs.getInt("id");String pw = rs.getString("pw");}System.out.println("id="+id);The results of a query are returned in a ResultSet object. The easiest wayto think of it is to c<strong>on</strong>sider it an iterator over the rows that result from thequery. In its simple form it is, like an iterator, a <strong>on</strong>e-pass, <strong>on</strong>ce-through traversalof the data. Since the result set is iterating over rows, we need to get at the individualcolumns of results with a further method call <strong>on</strong> the ResultSet. Youcan see that inside the while loop of the example.The query was built to retrieve the columns id and pw from our table.The getInt() and getString() methods use those column names to retrievethe data from the ResultSet.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!