package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; /** Test servlet for JDBC to perform the following operations on a table called test in the test database (this database is always available for testing in MySQL).
DROP TABLE IF EXISTS test; CREATE TABLE test ( name VARCHAR(20) NOT NULL, age INTEGER NOT NULL ); INSERT INTO test VALUES ('Fred', 34); SELECT * FROM test; Display the result DROP TABLE test;For a more object-oriented version see BookDisplayServlet */ public class DBaseTestServlet extends HttpServlet { private Connection connection; /** Load the database driver and make a connection */ public void init() throws ServletException { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/web_db", "c2206", "c2206"); } catch (ClassNotFoundException e) { System.out.println("Cannot load driver"); } catch (SQLException e) { System.out.println("Cannot make a connection"); } } /** Execute some SQL statements and queries */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = ""; int age = 0; response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { Statement st = connection.createStatement(); st.execute("DROP TABLE IF EXISTS test"); st.execute( "CREATE TABLE test (" + "name VARCHAR(20) NOT NULL," + "age INTEGER NOT NULL )" ); st.execute("INSERT INTO test VALUES ('Fred', 34)"); ResultSet result = st.executeQuery("SELECT * FROM test"); result.next(); // only one row name = result.getString("name"); age = result.getInt("age"); st.execute("DROP TABLE test"); } catch (SQLException e) { System.out.println("Error in statement"); } out.println("\n" + "