当前位置:Gxlcms > 数据库问题 > jsp_数据库的连接

jsp_数据库的连接

时间:2021-07-01 10:21:17 帮助过:26人阅读

<%@ 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>

四、在浏览器中显示:

技术分享

jsp_数据库的连接

标签:dstat   enter   配置   数据库操作   border   set   ble   使用   images   

人气教程排行