求助 大家好。帮我看看这个封装有什么缺陷。谢谢
下面是我封装的数据库。。大家帮我看看。有什么缺陷。最好详细点。谢谢各位帮我看看。。
package db;
import java.io.*;
import java.sql.*;
public class db {
public String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
public String ConStr = "jdbc:odbc:shop";
public String user = "sa";
public String pw = "sa";
Connection con = null;
ResultSet rs = null;
public String getStr(String s) {
String str = s;
try {
byte b[] = str.getBytes("ISO-8859-1");
str = new String(b);
return str;
} catch (Exception e) {
return null;
}
}
public String gb2iso(String qs) {
try {
if (qs == null) {
return "NULL";
} else {
return new String(qs.getBytes("gb2312"), "iso-8859-1");
}
} catch (Exception e) {
System.out.println("gb2iso error:" + e.getMessage());
}
return "NULL";
}
public void setDBDriver(String DBDriver) {
this.DBDriver = DBDriver;
}
public String getDBDriver() {
return DBDriver;
}
public void setConStr(String ConStr) {
this.ConStr = ConStr;
}
public String getConStr() {
return ConStr;
}
public void setuser(String user) {
this.user = user;
}
public String getuser() {
return user;
}
public void setpw(String pw) {
this.pw = pw;
}
public ResultSet query(String sql) throws Exception {
try {
Class.forName(DBDriver).newInstance();
con = DriverManager.getConnection(ConStr, user, pw);
Statement st = con.createStatement();
rs = st.executeQuery(sql);
return rs;
} catch (
SQLException ex) {
System.out.println("sql.executeQuery:" + ex.getMessage());
}
return null;
}
public void Close()
{
try {
con.close();
} catch (SQLException ex) {
}
}
public void update(String sql) throws Exception {
try {
Class.forName(DBDriver).newInstance();
con = DriverManager.getConnection(ConStr, user, pw);
Statement st = con.createStatement();
st.executeUpdate(sql);
con.close();
st.close();
} catch (SQLException ex) {
System.out.println("sql.executeUpdate:" + ex.getMessage());
}
}
}
------解决方案--------------------要说缺陷的话。
1。Class.forName(DBDriver).newInstance(); 这个东西调用一次就可以了,每次都执行没啥意思。
2.你那些close()应该写在finally{}里保证关闭数据链接,要不前头的出了异常,这个链接就没法释放了
con和st的关闭错误也反了,先关闭st再关闭con
其他的暂时没看出来。
------解决方案--------------------