81,091
社区成员
发帖
与我相关
我的任务
分享
package BaseUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigManager {
private static ConfigManager configManager;
private static Properties properties;
public ConfigManager(){
properties=new Properties();
String config="MysqlConn.properties";
InputStream inputStream=ConfigManager.class.getClassLoader().getResourceAsStream(config);
try {
properties.load( inputStream );
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ConfigManager getInstance(){
if (configManager==null)configManager=new ConfigManager();
return configManager;
}
public String getValue(String key){
return properties.getProperty( key );
}
}
public class BaseDao {
protected Connection conn;
protected PreparedStatement preparedStatement;
protected ResultSet resultSet;
public Connection getConn()throws Exception{
ConfigManager configManager=ConfigManager.getInstance();
String driver=configManager.getValue("driver" );
String url=configManager.getValue( "url" );
String username=configManager.getValue( "username" );
String password=configManager.getValue( "password" );
try {
Class.forName( driver );
conn= DriverManager.getConnection(url,username,password);
System.out.println("sucess");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public PreparedStatement ps(String sql, Object[]param) throws Exception {
this.getConn();
try {
preparedStatement=conn.prepareStatement( sql );
for (int i = 0; i <param.length ; i++) {
preparedStatement.setObject( i+1,param[i] );
}
} catch (SQLException e) {
e.printStackTrace();
}
return preparedStatement;
}
public ResultSet selectSql(String sql,Object[] param) throws Exception {
this.getConn();
this.ps( sql,param );
try {
resultSet =preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}finally {
this.releaseResource( resultSet,preparedStatement,conn );
}
return resultSet;
}
public void releaseResource(ResultSet resultSet, PreparedStatement preparedStatement,Connection con ){
try {
if (resultSet!=null)resultSet.close();
if (preparedStatement!=null)preparedStatement.close();
if (con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
src.main
↳java
↳resources
↳ druid.properties
target
↳ classes
↳ druid.properties