Oracle数据库中有多个表:Products,category等。
现在要连接数据库,获取Products表中的数据
1.写一个BaseDao用于连接数据库
package D0816;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
public static final StringDRIVER = "oracle.jdbc.OracleDriver";
public static final StringURL = "jdbc:oracle:thin:@localhost:1521:orcl";
public static final StringUSER_NAME = "lsh";
public static final StringUSER_PWD = "123456";
protectedConnection conn = null;
protectedPreparedStatement ps = null;
protectedResultSet rs = null;
static {
try {
Class.forName(DRIVER);
} catch(ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Connection getConn() {
try {
conn =DriverManager.getConnection(URL, USER_NAME, USER_PWD);
} catch(SQLException e) {
e.printStackTrace();
}
return conn;
}
voidcloseConn() {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.写一个CommonDao,其中有一个executeQuery方法来执行sql语句并返回执行的结果集,由于获取数据时,要查找的表格和要显示的表格和属性值会是变量,对应的pojo类和sql语句会是变量。
package D0816;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CommonDao extends BaseDao{
//传入sql语句与要查询的表格对应的pojo类
public List executeQuery(String sql,Class clazz){
List lst = new ArrayList<>();
super.getConn();//连接数据库
try {
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
Object o = clazz.newInstance();//利用反射机制实例化对象
Field[] fl = clazz.getDeclaredFields();//获取对象的属性
for(int i = 0;i<fl.length;i++){//轮流对每个属性值进行赋值
fl[i].setAccessible(true);
Object value = rs.getObject(fl[i].getName());//从数据库中获取的相应属性的值,由于类型不确定,使用Object
//由于数据库中的number类型是BigDecimal的,所以获取到的value是BigDecimal类型的,但是pojo中的数字定义成了Integer或Double属性。属性不同不能直接赋值,所以需要进行判断,将value的相应的转换成Integer或Double之后再输出
if(fl[i].getType()==Integer.class&&value.getClass()==java.math.BigDecimal.class){
BigDecimal v = (BigDecimal)value;
fl[i].set(o,v.intValue());
}else if(fl[i].getType()==Double.class&&value.getClass()==java.math.BigDecimal.class){
BigDecimal v = (BigDecimal)value;
fl[i].set(o, v.doubleValue());
}else{
fl[i].set(o, value);
}
}
lst.add(o);
}
} catch (SQLException | InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
super.closeConn();
}
return lst;
}
}
3.最后利用一个ProductsDao写要执行的sql语句和要查找的表格对应的pojo类,作为2中写好的CommonDao的executeQuery方法的参数去执行
package D0816;
import java.util.List;
public class ProductsDao extends CommonDao{
public List<Products> productsQuery(){
String sql = "select * fromproducts";
return super.executeQuery(sql,D0816.Products.class);
}
}
后期需要查找其他表格或要进行其他操作,只需修改CommonDao类中CommonDao的参数即可