Home  >  Article  >  Database  >  在JSP中用bean封装常用的功能_MySQL

在JSP中用bean封装常用的功能_MySQL

WBOY
WBOYOriginal
2016-06-01 14:10:52802browse

  
1、建立一个Bean



package guestbook;
import java.sql.*;
/**
* Title:用Javabean连接数据库
* Description:用Bean把常用的数据库功能封装,在JSP中声明该Bean。
* Copyright: Copyright (c) 2001
* Company:极速网络小组
* 编者:极速网络小组
* version 1.0
*/
public class sql_data
{
    String sDBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
    String sConnStr="jdbc:odbc:guestbook";
    Connection conn=null;
    ResultSet rs=null;
    public sql_data()
    {
        try{
            class.forName(sDBDriver);
        }
        catch(java.lang.ClassNotFoundException e)
        {
            System.err.println("sql_data():"+e.getMessage());
        }
    }



    public void executeInsert(String sql)
    {
        try
        {
            conn=DriverManager.getConnection(sConnStr);
            Statement stmt=conn.createStatement();
            stmt.executeUpdate(sql);
        }
        catch(SQLException ex)
        {
            System.err.println("sql_data.executeUpdate:"+ex.getMessage());
        }
    }



    public ResultSet executeQuery(String sql)
    {
        rs=null;
        try
        {
            conn=DriverManager.getConnection(sConnStr);
            Statement stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);
        }
        catch(SQLException ex)
        {
            System.err.println("sql_data.executeQuery:"+ex.getMessage());
        }
    }



    public void executeDelete(String sql)
    {
        try
        {
            conn=DriverManager.getConnection(sConnStr);
            Statement stmt=conn.createStatement();
            stmt.executeUpdate(sql);
        }
        catch(SQLException ex)
        {
            System.err.println("sql_data.executeDelete:"+ex.getMessage());
        }
    }
}



2、在JSP中声明Bean:



……





sql="select * from table";
ResultSet rs=sqlbean.executeQuery(sql);
while(rs.nex()){
    name=rs.getString("name")
}
%>
……
name:
……
rs.close();
%>
……

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn