19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

Class.forName("<strong>com</strong>.mysql.jdbc.Driver");<br />

System.out.println("Driver loaded");<br />

// Establish connection<br />

connection = DriverManager.getConnection<br />

("jdbc:mysql://localhost/javabook", "scott", "tiger");<br />

System.out.println("Database connected");<br />

// Create a statement for static SQL<br />

stmt = connection.createStatement();<br />

// Create a prepared statement <strong>to</strong> retrieve flag and description<br />

pstmt = connection.prepareStatement("select flag, description " +<br />

"from Country where name = ?");<br />

private void s<strong>to</strong>reDataToTable() {<br />

String[] countries = {"Canada", "UK", "USA", "Germany",<br />

"Indian", "China"};<br />

String[] imageFilenames = {"image/ca.gif", "image/uk.gif",<br />

"image/us.gif", "image/germany.gif", "image/india.gif",<br />

"image/china.gif"};<br />

String[] descriptions = {"A text <strong>to</strong> describe Canadian " +<br />

"flag is omitted", "British flag ...", "American flag ...",<br />

"German flag ...", "Indian flag ...", "Chinese flag ..."};<br />

try {<br />

// Create a prepared statement <strong>to</strong> insert records<br />

PreparedStatement pstmt = connection.prepareStatement(<br />

"insert in<strong>to</strong> Country values(?, ?, ?)");<br />

// S<strong>to</strong>re all predefined records<br />

for (int i = 0; i < countries.length; i++) {<br />

pstmt.setString(1, countries[i]);<br />

}<br />

// S<strong>to</strong>re image <strong>to</strong> the table cell<br />

java.net.URL url =<br />

this.getClass().getResource(imageFilenames[i]);<br />

InputStream inputImage = url.openStream();<br />

pstmt.setBinaryStream(2, inputImage,<br />

(int)(inputImage.available()));<br />

pstmt.setString(3, descriptions[i]);<br />

pstmt.executeUpdate();<br />

System.out.println("Table Country populated");<br />

}<br />

catch (Exception ex) {<br />

ex.printStackTrace();<br />

}<br />

}<br />

private void fillDataInComboBox() throws Exception {<br />

ResultSet rs = stmt.executeQuery("select name from Country");<br />

while (rs.next()) {<br />

jcboCountry.addItem(rs.getString(1));<br />

}<br />

34

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

Saved successfully!

Ooh no, something went wrong!