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.

15.4 Querying Data333// queryString mySQL = "SELECT id, pw FROM Users WHERE name = ?";PreparedStatement stmt = c<strong>on</strong>n.prepareStatement(mySQL);stmt.setString(1, args[0]);If you’re at all familiar with SQL then you’ll recognize the SQL syntaxwithin the String mySQL. Whatever you want your query to be, just build itas literal text. The query is “parameterized” by using the “?” character. Wherevera “?” appears in the query string, you can substitute a value with thesetString() method <strong>on</strong> the PreparedStatement class.There are a variety of setXXXX() methods where XXXX stands for differentdata types. Besides setString(), the most comm<strong>on</strong> <strong>on</strong>es are setInt(),setBigDecimal(), setDouble(), and setTimestamp() which set theparameter from an int, BigDecimal, Double, and Timestamp classes, respectively.The java.sql.Timestamp class is basically a java.util.Date augmentedfor compatibility with SQL’s noti<strong>on</strong> of TIMESTAMP. Read moreabout it <strong>on</strong> the Javadoc page for java.sql.Timestamp, or read thejava.sql.PreparedStatement page for more <strong>on</strong> the other set methodsavailable.The two arguments to each of these set methods are the index and thevalue that you want to substitute. The index is simply the count of whichquesti<strong>on</strong> mark gets substituted, starting with 1 for the first <strong>on</strong>e. Cauti<strong>on</strong>: Theparameters start at <strong>on</strong>e, even though most other things in Java, such as Arrays,ArrayLists, and so <strong>on</strong>, are zero-based. So it’s not uncomm<strong>on</strong> in code thatuses JDBC to see something like this:setInt(i+1, args[i]);NOTEBuilding SQL queries out of String literals is made easier in Java by a c<strong>on</strong>venientmismatch between the two languages. In Java, Strings are delimitedby double quotes (") whereas in SQL literals are bounded by single quotes('). Thus in Java, you can c<strong>on</strong>struct SQL queries that c<strong>on</strong>tain literal stringreferences without much trouble, as in:String clause = "WHERE name != 'Admin'"

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

Saved successfully!

Ooh no, something went wrong!