欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > Java架构 > JavaBean >

首先配置access数据源,数据源名称设为info.mdb,此文件放在test文件夹下,编译后将生成的infoBean.class放在claeese下的test文件夹下即可。

用access写个数据库info.mdb里面写个表student,两个字段id name。

这个是连接access的javaBean
package test;
import java.sql.*;
public class infoBean{
private String ab="sun.jdbc.odbc.JdbcOdbcDriver";
private String ac="JDBC:odbc:info.mdb";
Connection conn=null;
ResultSet rs=null;
Statement stmt;
public infoBean(){
try{
Class.forName(ab);}
catch(java.lang.ClassNotFoundException e){
System.out.println("infoBean():"+e.getMessage());}
}
public ResultSet executeQuery(String sql){
rs=null;
try{
conn=DriverManager.getConnection(ac);
stmt=conn.createStatement();
rs = stmt.executeQuery(sql);}
catch(SQLException ex){
System.err.println("aq.executeQuery:"+ex.getMessage());}
return rs;
}
public void executeUpdate(String sql)
{stmt=null;
rs=null;
try{
conn=DriverManager.getConnection(ac);
stmt=conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
conn.close();}
catch(SQLException e1)
{System.err.println("executeUpdate:" + e1.getMessage()); }
}
public void closeStmt()
{
try{
stmt.close();
}
catch (SQLException e2)
{
e2.printStackTrace();
}
}

public void closeConn()
{
try{
conn.close();
}
catch (SQLException e3)
{
e3.printStackTrace();
}
}
}

在jsp页面中引用时,显示数据库内容:
<%@ page contentType="text/html;charset=GB2312" import="java.sql.*" %>
<jsp:useBean id="inBean" class="test.infoBean" scope="page"/><html><head></head><body><table>
<tr><th>11</th><th>11</th></tr>
<%
ResultSet rs=inBean.executeQuery("SELECT * FROM student");
while rs.next(){
%>
<tr><td><%=rs.getString(1)%></td><td><%=rs.getString(2)%></td></tr>
<%}%>
</table></body></html>
在jsp中删除,
<%@ page contentType="text/html;charset=GB2312" import="java.sql.*" %>
<jsp:useBean id="inBean" class="test.infoBean" scope="page"/><html><head></head><body>
<%
String id=request.getParameter("id");
inBean.executeUpdate("Delete from student where id='"+id+"'");
%>
</body></html>
其中id是上一个页面传过来的;
jsp中修改:
<%@ page contentType="text/html;charset=GB2312" import="java.sql.*" %>
<jsp:useBean id="inBean" class="test.infoBean" scope="page"/><html><head></head><body>
<%
String id=request.getParameter("id");
String name=request.getParameter("name");

inBean.executeUpdate("update student set name='"+name+"' where id='"+id+"'");
%>
</body>
</html>

    相关教程
    推荐内容