为了确保一个java类成为JavaBean,有以下四个简单的也是必须的规范:
(1)JavaBean 类必须是一个公共类,并将其访问属性设置为 public
(2)JavaBean 类必须有一个空的构造函数:类中必须有一个不带参数的公用构造器,此构造器也应该通过调用各个特性的设置方法来设置特性的缺省值。
(3)一个javaBean类不应有公共实例变量,类变量都为private
(4)持有值应该通过一组存取方法(getXxx 和 setXxx)来访问:对于每个特性,应该有一个带匹配公用 getter 和 setter 方法的专用实例变量。
示例代码:
package show;
import java.sql.*;
public class DBconn
{
private String sDBDriver = "org.gjt.mm.mysql.Driver";
private String sConnStr = "jdbc:mysql://10.1.1.79:3306/web?user=root&password=2676141";
private Connection conn = null;
private ResultSet rs = null;
public DBconn()
{
try
{
Class.forName(sDBDriver);
}
catch(ClassNotFoundException e)
{
System.out.println("DBconn():" + e.getMessage());
}
}
public String getsConnStr()
{
return sConnStr;
}
public void setsConnStr(String sConnStr)
{
this.sConnStr = sConnStr;
}
public void executeUpdate(String sql) throws Exception
{
sql = new String(sql.getBytes("GBK"),"ISO8859_1");
try
{
conn=DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
conn.close();
stmt.close();
}
catch(SQLException ex)
{
System.out.println("sql.executeUpdate:" + ex.getMessage());
}
}
public ResultSet executeQuery(String sql) throws Exception
{
rs = null;
try
{
sql = new String(sql.getBytes("GBK"),"ISO8859_1");
conn = DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
conn.close();
stmt.close();
}
catch(SQLException ex)
{
System.out.println("sql.executeQuery:" + ex.getMessage());
}
return rs;
}
}