BaseDao

阅读更多

//刚开始的时候用的这个
public class BaseDao {

private Connection conn;
private PreparedStatement stmt;
private ResultSet rs;

//创建链接
public Connection getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/liubao2";
String user="root";
String password="123456";
conn=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}


//关闭连接
public void close(){       

try {
if(rs!=null){
rs.close();
}

if(stmt!=null){
stmt.close();
}

if(conn!=null){
conn.close();
}


} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//修改的操作
public boolean executeUpdate(String sql,Object[] parameters){

try {
getConnection();
stmt=conn.prepareStatement(sql);
//占位符 参数赋值
if(parameters !=null){
for(int i=0;i stmt.setObject(i+1,parameters[i]);
}
}

int count=stmt.executeUpdate();

close();
return count>0?true:false;

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

//查询的操作  ResultSet 
public ResultSet getResultSet(String sql,Object[] parameters){
   
try {
getConnection();
stmt=conn.prepareStatement(sql);
//占位符 参数赋值
if(parameters !=null){
for(int i=0;i stmt.setObject(i+1,parameters[i]);
}
}
rs=stmt.executeQuery();
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}


//将ResultSet --->List

public List executeQuery(String sql,Object[] parameters,Class c){
 
rs=getResultSet(sql,parameters);
List list=JDBCUtil.convertResultSetToList(c, rs);
close();
return list;
}


//ResultSet ---单个的实体
public T executeSingle(String sql,Object[] parameters,Class c){
rs=getResultSet(sql,parameters);
T t=JDBCUtil.convertResultSetToEntity(c, rs);
return t;
}

//计算总数的方法
public int getCounts(String sql, Object[] parameters) {
// TODO Auto-generated method stub

try {
getConnection();
stmt=conn.prepareStatement(sql);
if(parameters!=null){
for(int i=0;i stmt.setObject(i+1, parameters[i]);
}
}
rs=stmt.executeQuery();
int count=0;
while(rs.next()){
count=rs.getInt(1);
}
close();
return count;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}

}



}
--奋斗的刘啊宝

你可能感兴趣的:(jdbc,java,basedao)