:D
//剛開始的時候用的這個 :shock:
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<parameters.length;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<parameters.length;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<T>
public <T> List<T> executeQuery(String sql,Object[] parameters,Class<T> c){
rs=getResultSet(sql,parameters);
List<T> list=JDBCUtil.convertResultSetToList(c, rs);
close();
return list;
}
//ResultSet ---單個的實體
public <T> T executeSingle(String sql,Object[] parameters,Class<T> 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<parameters.length;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;
}
}
}
--奮鬥的劉啊寶