1、项目结构:
2、数据库
3、PropertiesTool.java:
package com.tool;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesTool {
private static Properties properties = new Properties();
static {
InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getValue(String key) {
return properties.getProperty(key);
}
}
4、DBLink.java:
package com.tool.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import com.jd.tool.PropertiesTool;
/**
* 数据库管理工具类
*
* @author 10164
*/
public class DBLink {
private Logger logger=Logger.getLogger(DBLink.class);
/**
* 获取数据库链接
*
* @author 10164
*/
private Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String userName = PropertiesTool.getValue("db.username");
String password = PropertiesTool.getValue("db.password");
String url = PropertiesTool.getValue("db.url");
return DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
logger.debug(e.getMessage(),e);
}
return null;
}
/**
* 查询数据
*
* @author 10164
*/
public void select(String sql,IRowMapper rowMapper) {
Connection connection = null;
Statement statement =null;
ResultSet resultSet=null;
try {
connection=getConnection();
statement = connection.createStatement();
resultSet= statement.executeQuery(sql);
rowMapper.rowmapper(resultSet);
} catch (Exception e) {
logger.debug(e.getMessage(),e);
}finally {
close(resultSet,statement,connection);
}
}
/**
* 修改数据
*
* @author 10164
*/
public boolean update(String sql) {
Connection connection=null;
Statement statement=null;
try {
connection=getConnection();
statement=connection.createStatement();
int result=statement.executeUpdate(sql);
//statement.close();
//connection.close();
return result>0;
}catch(Exception e) {
logger.debug(e