通过JDBC连接数据库(MySql为例)并读取数据库信息--JSP基础
1、先建数据库,数据库名为:employee_DB;然后在数据库employee_DB下建表,表名为employee;最后插入数据。
create database employee_DB;
use employee_DB;
create table employee(
id int primary key auto_increment,
name varchar(50),
age int,
sex varchar(2),
salary float,
department varchar(50)
);
desc employee;
insert into employee values(1,'张雨',20,'女',3600,'后勤部');
insert into employee values(2,'刘冰',22,'男',4500,'人事');
insert into employee values(3,'张雨',25,'男',5000,'技术部');
select * from employee;
2、index.jsp页面:
1 <%@page import="java.sql.ResultSet"%>
2 <%@page import="java.sql.Statement"%>
3 <%@page import="java.sql.Connection"%>
4 <%@page import="java.sql.DriverManager"%>
5 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
6 <%
7 String path = request.getContextPath();
8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
9 %>
10
11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
12 <html>
13 <head>
14 <base href="<%=basePath%>">
15
16 <title>My JSP 'index.jsp' starting page</title>
17 <meta http-equiv="pragma" content="no-cache">
18 <meta http-equiv="cache-control" content="no-cache">
19 <meta http-equiv="expires" content="0">
20 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
21 <meta http-equiv="description" content="This is my page">
22
23 </head>
24
25 <body>
26 <%
27 try{
28 Class.forName("com.mysql.jdbc.Driver");
29 //out.print("加载驱动成功……");
30 }catch(ClassNotFoundException e){
31 //out.print("加载驱动出现异常!");
32 //out.print(e);在浏览器下输出异常
33 e.printStackTrace();
34 }
35 String url="jdbc:mysql://localhost:3306/employee_db";
36 String username="root";
37 String password="123456";
38 Connection conn=DriverManager.getConnection(url, username, password);
39 /*
40 if(conn!=null){
41 out.print("数据库连接成功!");
42 conn.close();
43 }else{
44 out.print("数据库连接失败!");
45 }
46
47 */
48 Statement stmt=conn.createStatement();
49 String sql="select * from employee";
50 ResultSet rs=stmt.executeQuery(sql);
51 %>
52 <%
53 %>
54 <table border=2>
55 <tr>
56 <th>员工号</th>
57 <th>姓名</th>
58 <th>年龄</th>
59 <th>性别</th>
60 <th>薪水</th>
61 <th>部门</th>
62 </tr>
63 <%
64 while(rs.next()){
65 out.print("<tr>");
66 out.print("<td>"+rs.getInt("id")+"</td>");
67 out.print("<td>"+rs.getString("name")+"</td>");
68 out.print("<td>"+rs.getString("age")+"</td>");
69 out.print("<td>"+rs.getString("sex")+"</td>");
70 out.print("<td>"+rs.getFloat("salary")+"</td>");
71 out.print("<td>"+rs.getString("department")+"</td>");
72 out.print("</tr>");
73 }
74 out.print("</table>");
75 rs.close();
76 stmt.close();
77 conn.close();
78 %>
79 </body>
80 </html>