封装的数据库访问类

 package javaBeans; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.*; import java.util.Properties; import javax.sql.rowset.CachedRowSet; import com.sun.rowset.CachedRowSetImpl; import com.mysql.jdbc.*; public class DBAccess { private java.sql.Connection con; private java.sql.PreparedStatement preparedStatement=null; private java.sql.Statement statement=null; private String DRIVERCLASS=null; private String userName=null; private String userPassword=null; private String url=null; private String cmdstr=null; public DBAccess(String sql) { try { InitConnParam(); Class.forName(DRIVERCLASS); con=DriverManager.getConnection(url,userName,userPassword); cmdstr=sql; } catch(Exception e) { e.printStackTrace(); } } private void InitConnParam() { Properties p=new Properties(); try { p.load(new FileInputStream("D://我的文档//workspace//MessageBoard//DriverInfo.properties")); //p.load(new FileInputStream("/DriverInfo.properties")); DRIVERCLASS=p.getProperty("DRIVERCLASS"); userName=p.getProperty("userName"); userPassword=p.getProperty("userPassword"); url=p.getProperty("url"); //String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd; } catch (FileNotFoundException e) { System.out.println("找不到DriverInfo.properties"); e.printStackTrace(); } catch (IOException e) { System.out.println("加载DriverInfo.properties失败"); e.printStackTrace(); } } public boolean executePreparedStatement() { try { preparedStatement.executeUpdate(); con.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public CachedRowSet execStatement() throws SQLException { CachedRowSet cachedRowSet=new CachedRowSetImpl();; try { cachedRowSet.setCommand(cmdstr); cachedRowSet.execute(con); con.close(); } catch(Exception e) { System.out.println("execStatement()执行时发生异常。"); e.printStackTrace(); } return cachedRowSet; } public void setString(int index,String param) throws SQLException { if(preparedStatement==null) preparedStatement=con.prepareStatement(cmdstr); preparedStatement.setString(index, param); } public void setInt(int index,int param) throws SQLException { if(preparedStatement==null) preparedStatement=con.prepareStatement(cmdstr); preparedStatement.setInt(index, param); } public void setDate(int index,Date param) throws SQLException { if(preparedStatement==null) preparedStatement=con.prepareStatement(cmdstr); preparedStatement.setDate(index,param); } public void setDouble(int index,double param)throws SQLException { if(preparedStatement==null) preparedStatement=con.prepareStatement(cmdstr); preparedStatement.setDouble(index,param); } }

你可能感兴趣的:(封装的数据库访问类)