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