import java.sql.*; public class JDBCEx1 { public static void main(String args[]) { Connection conn = null; Statement s = null; int count; try { /* getConnection */ Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "yaleyal3"); if(!conn.isClosed()) System.out.println("Successfully connected to " + "MySQL server using TCP/IP..."); /* executeUpdate */ s = conn.createStatement(); s.executeUpdate("DROP TABLE IF EXISTS animal"); s.executeUpdate( "CREATE TABLE animal (" + "id INT UNSIGNED NOT NULL AUTO_INCREMENT," + "PRIMARY KEY (id)," + "name CHAR(40), category CHAR(40))"); count = s.executeUpdate( "INSERT INTO animal (name, category)" + " VALUES" + "('snake', 'reptile')," + "('frog', 'amphibian')," + "('tuna', 'fish')," + "('racoon', 'mammal')"); System.out.println(count + " rows were inserted"); /* executeQuery */ s.executeQuery("SELECT id, name, category FROM animal"); ResultSet rs = s.getResultSet(); count = 0; while (rs.next()){ int idVal = rs.getInt("id"); String nameVal = rs.getString("name"); String catVal = rs.getString("category"); System.out.println( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } System.out.println(count + " rows were retrieved"); conn.close(); s.close(); rs.close(); } catch(Exception e) { System.err.println("Exception: " + e.getMessage()); } } }