java bean 的问题
/*****************************
* 数据库连接 bean ,用来连接 MySQL数据库
*****************************/
package com.teach;
import java.sql.*;
public class mysql
{
Connection conn;
ResultSet rs;
Statement stmt;
public mysql()
{
try
{
//连接MySQL数据库的字符串
String cstr= "jdbc:mysql://localhost:3306/new_db?useUnicode=true&characterEncoding=GBK ";
//装载MySQL数据库的驱动程序
Class.forName( "com.mysql.jdbc.Driver ").newInstance();
//创建连接
conn= java.sql.DriverManager.getConnection(cstr, "root ", "12345 ");
//创建Statement
stmt=conn.createStatement();
} catch(
SQLException ex){ System.out.println(ex.getMessage()); }
catch(Exception e){ System.out.println( "createError: "+e.getMessage());}
}
public ResultSet query(String sql)
{
try{
//执行查询SQL语句得到Resultset(记录集)
rs=stmt.executeQuery(sql);
}catch(SQLException ex){System.out.println( "executeQuery: "+ex.getMessage());}
return rs;
}
public void executeUpdate(String sql)
{
try{
//执行操作数据库SQL语句的方法,如插入、删除、更新记录
stmt.executeUpdate(sql);
}catch(SQLException e){ System.out.println( "excecuteUpdate: "+e.getMessage());}
}
//关闭resultset、statement和connection
public void close()
{
try{
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
}catch(SQLException e){
System.err.println(e.getMessage()); }
}
}
用于显示数据库内容的jsp文件
<!-dispStudent.jsp-->
<!-显示学生名单的JSP页面-->
<!--设置中文输出-->
<%@ page language= "java " contentType= "text/html;charset=gb2312 " %>
<!-导入JAVA.SQL包-->
<%@ page import= "java.sql.* "%>
<!--设置需要调用的JavaBean,即编写的Java类-->
<jsp:useBean id= "sqlBean " scope= "page " class= "com.teach.mysql "/>
<html>
<head> <title> 学生名单 </title> </head>
<body>
<%
ResultSet rs;
//增加新记录
sqlBean.executeUpdate( "INSERT INTO student VALUES ( '040001 ', '王海 ', '男 ', '计算机应用 ', '04112 ') ");
//查询记录
rs = sqlBean.query( "select * from student ");
//输出查询结果
out.println( " <table border=1 width=400> ");
while (rs.next())
{
String sno = rs.getString(1);
String sname = rs.getString(2);
String ssex = rs.getString(3);
String special = rs.getString(4); <