java web的后缀名是jsp,因此我们要有一个jsp的开发环境,我这用的是jspStudyhtml
自行百度。这软件是一个集成开发环境,安装启动后便可使用,集成了tomcat和mysql数据库java
首先咱们先新建一个首页文件mysql
index.jspweb
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.Connection" %> <%@ page import="java.sql.DriverManager" %> <%@ page import="java.sql.SQLException" %> <%@ page import="java.sql.Statement" %> <%@ page import="java.sql.PreparedStatement" %> <%@ page import="java.sql.ResultSet" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mysql测试</title> </head> <body> <% //此进行链接数据库 String url="jdbc:mysql://127.0.0.1:3306/test"; //test为数据库名称 String dbuser="root"; //数据库帐户 String dbpwd="root"; //数据库密码 try { Class.forName("com.mysql.jdbc.Driver"); //加载驱动 JspStudy } catch (ClassNotFoundException e) { e.printStackTrace(); } //取得数据库链接conn Connection conn=DriverManager.getConnection(url, dbuser, dbpwd);; PreparedStatement ps=null; ResultSet rs=null; //声明数据库字段 String id=""; String title=""; String img=""; try { String sql="select * from res"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { id=rs.getString(1); title=rs.getString(2); img=rs.getString(3); out.println("ID:"+id+"<br>"); out.println(title+"<br><br>"); out.println("<img src=\""+img+"\"/>"+"<br><br>"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(ps!=null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } %> </body> </html>
而后拷贝到jspStudy的WWW目录
在浏览器输入http://localhost/index.jsp
便可运行。sql
固然数据库的数据要有数据库
这是我这边数据库的结构浏览器
最终效果:tomcat