servelet 连接mysql
2015-08-04 10:39
627 查看
package helloworld; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** */ @WebServlet("/HelloWorld") public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public HelloWorld() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = null; Statement stmt = null; ResultSet rs = null; response.setContentType("text/html"); response.setCharacterEncoding("gb2312"); PrintWriter out = response.getWriter(); out.println("<table border=1>"); out.println("<tr><td>查询结果</td></tr>"); try{ Class.forName("com.mysql.jdbc.Driver"); //lib conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gs?user=root&password=root"); stmt = conn.createStatement(); rs = stmt.executeQuery("select * from user"); while(rs.next()){ out.println("<tr>"); out.println("<td>"+rs.getString("name")+"</td>"); out.println("</tr>"); } out.println("</table>"); }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (SQLException e){ e.printStackTrace(); } finally{ try{ if(rs !=null){ rs.close(); rs=null; } if(stmt != null){ stmt.close(); stmt=null; } if(conn!=null){ conn.close(); conn=null; } } catch(SQLException e){ e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html><head><title>helloworld</title><head><body>hello world!!!</body></html>"); } }
相关文章推荐
- Ubuntu下忘记MySQL root密码解决方法
- [转] mysql中insert into select和create select用法
- Mysql参数
- mysql_real_connect连接问题
- MySQL MyISAM/InnoDB高并发优化经验
- MySQL初学者入门教程
- mysql登录报错ERROR 1045 (28000的解决方法
- mysql 多表联查
- MySQL数据库与表创建常用命令
- MySQL调优 —— Using temporary
- Mysql连接查询
- 测试mysql查询中参数整形和字符串类型错误索引使用情况
- MySQL开发规范之我见
- mysql之日志和mysqlbinlog工具的使用
- MySQL学习笔记_如何选择合适的存储引擎
- Mysql 多实例配置与启停
- MySQL查询子句(group by,limit,union,order by等)
- MySQL5.6主从复制(读写分离)
- MySQL性能优化
- MySQL中的datetime与timestamp比较