WEB开发网
开发学院WEB开发Jsp 一个javabean轻松实现对数据库的各种操作 阅读

一个javabean轻松实现对数据库的各种操作

 2008-01-05 09:36:41 来源:WEB开发网   
核心提示: 1.调用实例 <%@ page contentType="text/Html" import="Operate_db.*,java.sql.*"%> <jsp:useBean i


1.调用实例
<%@ page contentType="text/Html" import="Operate_db.*,java.sql.*"%>
<jsp:useBean id="querybean" scope="request" class="operate_db.QueryBean" />
<%
String PRm1,prm2,prm3;
ResultSet rst=null;
prm1 = ...;
prm2 = ...;
prm3 = ...;
querybean.setConnection("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:数据源名","sa","");

try{

String[] param = {prm1,prm2,prm3};
/*设置select语句*/
querybean.setQuerystatement("Select * from table where field1 = ? and field2=? and field3=?");
querybean.setParam(param);
rst=querybean.getResult();
}catch(Exception e){System.out.println(e); }

while (rst.next()){

%><%=rst.getString(1)%>

<%}%>
2.javabean QueryBean

QueryBean.java:

pacakage operate_db;
/**
* Title: select insert update and delete
* Description: select insert update and delete
* Copyright: Copyright (c) 2001
* @author Lci21
* @version 1.0
*/

import java.sql.*;
public class QueryBean
{
public String query_statement; /*定义sql语句*/
public String param[]; /*查询条件,或者是新的记录*/
public ResultSet result=null;
public Connection conn;

public void setParam(String[] param)
{
this.param=param;
}
public void setQuerystatement(String query_statement)
{
this.query_statement=query_statement;
}
public void setConnection(String driverName,String jdbcURL,String username,String passwd) throws Exception
{
Connection conn1;
Class.forName(driverName);
conn1=DriverManager.getConnection(jdbcURL,username,passwd);
conn1.setAutoCommit(false);
this.conn = conn1;
}
/*获取查询结果*/
public ResultSet getResult()
{
try
{
PreparedStatement select_stm=conn.prepareStatement(query_statement,java.sql.ResultSet.TYPE_SCROLL_INSENS99vIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
if (param!=null)
for(int i=0;i<param.length;i++)
select_stm.setString(i+1,param[i]);
result=select_stm.executeQuery();
}catch(Exception e){System.out.println(e);}
return result;
}


Tags:一个 javabean 轻松

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接