01_10_servlet How to connect to MySQL database

Source: Internet
Author: User
Tags stmt

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.