01_10_servlet How to connect to Mysql database 1.
Implementation Class
Public void doget (httpservletrequest request, httpservletresponse response)
throws Servletexception, IOException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ");
Out.println ("<HTML>");
Out.println ("connection to MySQL database </title>);
Out.println ("<BODY>");
Out.print ("<table align=\" Center\ "border=\" 1\ "><tr align=\" center\ "><td> query World the Name column information in the city table in the library </td></tr> ");
Try {
Class. forname ("Com.mysql.jdbc.Driver");
conn = DriverManager. getconnection ("jdbc:mysql://localhost:3306/world?user=root&password=123456");
stmt = (Statement) conn.createstatement ();
rs = Stmt.executequery ("SELECT * from City");
while (Rs.next ()) {
Out.println ("<tr align=\" Center\ "><td>" +rs.getstring ("name") + "</td></tr>");
}
Out.println ("</table>");
} catch (ClassNotFoundException e) {
E.printstacktrace ();
} catch (SQLException e) {
E.printstacktrace ();
} finally {
if (rs! = null) {
Try {
Rs.close ();
rs = null;
} catch (SQLException e) {
E.printstacktrace ();
}
}
if (stmt! = null) {
Try {
Stmt.close ();
stmt = null;
} catch (SQLException e) {
E.printstacktrace ();
}
}
if (conn! = null) {
Try {
Conn.close ();
conn = null;
} catch (SQLException e) {
E.printstacktrace ();
}
}
}
Out.println ("</BODY>");
Out.println ("</HTML>");
Out.flush ();
Out.close ();
}
01_10_servlet How to connect to MySQL database