某*.properties文件内容例如:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://1.14.XXX.XX:3306/smart_search?useUnicode=true&characterEncoding=utf-8 username=root password=159357
若是普通javaweb项目,properties文件放在src中
若是maven项目,properties文件放在resources文件中
使用方法在如下方法封装中已体现
1.创建utils包-->创建JDBCutils类
2.封装静态方法,具体如下
//获取数据库链接
public static Connection getConnection() throws Exception {
ClassLoader classLoader= JDBC.class.getClassLoader();
InputStream in=classLoader.getResourceAsStream("db.properties");
Properties pop=new Properties();
pop.load(in);
String driver=pop.getProperty("driver");
String url=pop.getProperty("url");
String dbUserName=pop.getProperty("username");
String dbPassword=pop.getProperty("password");
Class.forName(driver);
Connection connection= DriverManager.getConnection(url,dbUserName,dbPassword);
return connection;
}
//关闭链接和PreparedStatement
public static void closeResource(Connection conn, PreparedStatement ps){
try{
if(ps!=null)
ps.close();
}catch (SQLException e){
e.printStackTrace();
}
try{
if(conn!=null)
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
//关闭链接和PreparedStatement和ResultSet
public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
try{
if(ps!=null)
ps.close();
}catch (SQLException e){
e.printStackTrace();
}
try{
if(conn!=null)
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
try{
if(rs!=null)
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
}
//通用的增删改,这里不建议void,因为要判断是否执行成功
public static void update(String sql,Object... args){
Connection conn=null;
PreparedStatement ps=null;
try{
conn=JDBC.getConnection();
ps=conn.prepareStatement(sql);
for(int i=0;i
//通用的查询(能够针对不同表、查询一条记录、返回一个Bean、动态的)
public staticT selectForBean(Class clazz,String sql,Object... args){ Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try{ conn=JDBC.getConnection(); ps=conn.prepareStatement(sql); for(int i=0;i
//通用的查询(能够针对不同表、用于查询多条记录、返回一个集合、动态的)
public staticList selectForList(Class clazz, String sql, Object... args){ Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try{ conn=JDBC.getConnection(); ps=conn.prepareStatement(sql); for(int i=0;i list=new ArrayList (); while (rs.next()){ //获取对应的无参构造器 T t=clazz.newInstance(); //处理结果集一行数据中的每一个列 for(int i=0;i



