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.

330Chapter 15Accessing the Data: An Introducti<strong>on</strong> to JDBCExample 15.1 Simple sample program using JDBC for MySQLimport java.sql.*;public classMyC<strong>on</strong>{public static voidmain(String [] args){try {// A simple c<strong>on</strong>necti<strong>on</strong> example looks like this:Class.forName("com.mysql.jdbc.Driver").newInstance();String url = "jdbc:mysql://host.domain.com/test"+"?user=blah&password=blah";C<strong>on</strong>necti<strong>on</strong> c<strong>on</strong>n = DriverManager.getC<strong>on</strong>necti<strong>on</strong>(url);// queryString mySQL = "SELECT id, pw FROM Users WHERE name = ?";PreparedStatement stmt = c<strong>on</strong>n.prepareStatement(mySQL);stmt.setString(1, args[0]);// execute the queryResultSet rs = stmt.executeQuery();// read the resultswhile(rs.next()) {int id = rs.getInt("id");String pw = rs.getString("pw");System.out.println("id="+id);}} catch (Excepti<strong>on</strong> e) {System.out.println("Excepti<strong>on</strong>: "+e);e.printStackTrace();}} // main} // class MyC<strong>on</strong>

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

Saved successfully!

Ooh no, something went wrong!