ninic

导航

jsp_数据库的连接

一、添加数据库以及表

在这里我们使用的是mysql数据库

二、配置数据库的驱动程序

将mysql的驱动程序复制到Tomcat目录下的lib目录中

注:在Tomcat中如果配置了新的jar包,则配置完成后一定要重新启动服务器。

三、在jsp文件中获取数据库的连接,并将前面创建的表的数据显示出来

 1 <%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
 2 <!doctype html>
 3 <html>
 4 <head>
 5 <meta charset="utf-8">
 6 <title>连接数据库</title>
 7 </head>
 8 <body>
 9     <%!
10         public static final String dbdriver="com.mysql.jdbc.Driver";  //数据库驱动
11         public static final String dburl="jdbc:mysql://localhost:3306/test"; //数据库连接地址
12         public static final String dbuser="root"; //用户名
13         public static final String dbpass="a"; //密码
14     %>
15     <%
16         request.setCharacterEncoding("utf-8");
17         Connection conn=null;  //声明数据库连接对象
18         PreparedStatement pstmt=null;  //声明数据库操作
19         ResultSet rs=null;   //声明数据库结果集
20     %>
21     <%
22         //数据库操作会出现异常,所以要使用try catch处理
23         try{
24             Class.forName(dbdriver); //数据库驱动程序加载
25             conn=DriverManager.getConnection(dburl,dbuser,dbpass);  //获取数据库的连接
26             String sql="select * from user";
27             pstmt=conn.prepareStatement(sql);
28             rs=pstmt.executeQuery(); //执行查询操作
29     %>
30     <center>
31         <table border="1" width="50%">
32             <tr>
33                 <th>用户编号</th>
34                 <th>用户姓名</th>
35                 <th>用户年龄</th>
36             </tr>
37             <%
38                 while(rs.next()){
39                     int uid=rs.getInt(1);
40                     String uname=rs.getString(2);
41                     int uage=rs.getInt(3);        
42                 
43             %>
44             <tr>
45                 <td><%=uid%></td>
46                 <td><%=uname%></td>
47                 <td><%=uage%></td>
48             </tr>
49             <%
50                 }
51             %>
52         </table>
53     </center>
54     <%
55         }catch(Exception e){
56             System.out.println(e);    
57         }finally{
58             rs.close();
59             pstmt.close();
60             conn.close();
61         }
62     %>
63 </body>
64 </html>

四、在浏览器中显示:

posted on 2016-10-29 20:54  ninic  阅读(842)  评论(0编辑  收藏  举报