数据库的连接
既然page指令中存在import属性,所以导包就可以正确的使用了。需要说明的是,在整个page指令属性中只有import语句可以多次使用,其他的只能用一次。
既然可以出现可以使用JDBC完成。首先打开数据库 数据库中有一个表 表明user
empno | ename | sal | hiredate | job |
6060 | 李兴华 | 2000.3 | 2001-09-16 | 经理 |
6067 | 李兴华 | 2000.3 | 2001-09-16 | 经理 |
7369 | 杨军 | 1500.9 | 2003-10-01 | 分析员 |
7698 | 王月 | 1000.0 | 2006-09-01 | 经理 |
8964 | 刘明 | 2500.0 | 2005-01-12 | 销售 |
希望可以通过JSP进行列表的输出,下面可以开始编写程序了,但是Mysql数据库里连接的时候需要额外的驱动程序,将驱动程序拷贝到TOMCAT安装目录中的lib文件夹下,注意:这时候必须重启服务器,服务器重新启动之后才能将新的配置读取出来。
下面我会把驱动程序传到博客上面去mysql-connector-java-5.1.7-bin.jar
接下来我们开始编写程序 。
<%!public static String DBDRIVER=
"com.mysql.jdbc.Driver";
public static final String DBURL=
"jdbc:mysql://localhost:3306/test";
public static final String DUSER="root";
public static final String DBPASS="";
%>
上面这段代码是mysql的连接操作,第一句是驱动程序。
<%!public static String DBDRIVER=
"com.mysql.jdbc.Driver";
第二个是连接数据库jdbc:mysql://localhost:3306/是不变的 后面跟上数据库的名称test
public static final String DBURL=
"jdbc:mysql://localhost:3306/test";
第三句是用户名,一般是root,第四句是密码,我设置的密码为空。
然后我们需要导包<%@ page import="java.sql.*" %>
接下来我们写连接的一系列对象和操作
<%
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
%>
这里面有异常。不管如何最后要依次操作。
<% try{
%>
<% }catch(Exception e){
System.out.println(e);
}finally{
rs.close();
pstmt.close();
conn.close();//如果直接关闭连接也可以
}
%>
然后就开始插入SQL语句,在try中操作。
<% try{
Class.forName(DBDRIVER);
conn=DriverManager.getConnection(DBURL,DUSER,DBPASS);
//查询的时候必须写出具体字段不能出现*
String sql="SELECT empno,ename,sal,hiredate,job FROM user";
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);
float sal=rs.getFloat(3);
java.util.Date date=rs.getDate(4);
String job=rs.getString(5);
%>
//依次的列表输出
<tr>
<td><%=empno%></td>
<td><%=ename%></td>
<td><%=sal%></td>
<td><%=date%></td>
<td><%=job%></td>
</tr>
<%} %>
</table>
</center>
代码执行后就把数据库中所有内容都显示出来了。
雇员编号 | 雇员姓名 | 工资 | 日期 | 职位 |
6060 | 李兴华 | 2000.3 | 2001-09-16 | 经理 |
6067 | 李兴华 | 2000.3 | 2001-09-16 | 经理 |
7369 | 杨军 | 1500.9 | 2003-10-01 | 分析员 |
7698 | 王月 | 1000.0 | 2006-09-01 | 经理 |
8964 | 刘明 | 2500.0 | 2005-01-12 | 销售 |
OVER