我将Jsp连接Mysql数据库方法整理如下,供大家学习交流!
1、首先在myslq数据库中新建mldn数据库,并新建emp表。(方法不展开介绍)
插入数据如下:
create table `emp` ( `empno` int (4), `ename` varchar (30), `job` varchar (27), `hiredate` date , `sal` float ); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('6060','李兴华1','经理','2001-09-16','2000.30'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('7369','董鸣楠','销售','2003-10-09','1500.90'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('7698','张惠','销售','2005-03-12','800.00'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('7762','刘明','销售','2005-03-09','1000.00'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('7782','杨军','分析员','2005-01-12','2500.00'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('7839','王月','经理','2006-09-01','2500.00'); insert into `emp` (`empno`, `ename`, `job`, `hiredate`, `sal`) values('8964','李祺','分析员','2003-10-01','3000.00');
2、数据库和表准备好后,下载Mysql的驱动程序,放在工程lib目录下:
驱动程序网盘下载:https://yunpan.cn/ckRPAjwDd985G 访问密码 d77d
注意:工程中配置了新的jar包,则配置完成后一定要重启服务器,只有这样,才能将新配置的jar包在服务器启动时加载进来,不会出现找不到驱动程序的错误。
3、编写jsp代码文件:list_emp.jsp
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="java.sql.*"%> <!-- 导入的mysql驱动包 --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'list_emp.jsp' starting page</title> </head> <body> <%! public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; public static final String DBURL = "jdbc:mysql://localhost:3306/mldn" ; public static final String DBUSER = "wangyan" ; public static final String DBPASS = "123456" ; %> <% Connection conn = null ; PreparedStatement pstmt = null ; ResultSet rs = null ; %> <% try{ Class.forName(DBDRIVER) ; conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ; String sql = "SELECT empno,ename,job,sal,hiredate FROM emp" ; pstmt = conn.prepareStatement(sql) ; rs = pstmt.executeQuery() ; %> <center> <table border="1" width="80%"> <tr> <td>雇员编号</td> <td>雇员姓名</td> <td>雇员工作</td> <td>雇员工资</td> <td>雇佣日期</td> </tr> <% while(rs.next()){ int empno = rs.getInt(1) ; String ename = rs.getString(2) ; String job = rs.getString(3) ; float sal = rs.getFloat(4) ; java.util.Date date = rs.getDate(5) ; %> <tr> <td><%=empno%></td> <td><%=ename%></td> <td><%=job%></td> <td><%=sal%></td> <td><%=date%></td> </tr> <% } %> </table> </center> <% }catch(Exception e) { System.out.println(e) ; }finally{ rs.close() ; pstmt.close() ; conn.close() ; // 如果直接关闭连接也可以 } %> </body> </html>
在浏览器输入地址后,展示出从emp表中查询的数据,如图: