package cn.jbit.cms.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
//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 java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import cn.jbit.cms.entity.News;
/**
* 数据库连接与关闭工具类
* @author Administrator
*
*/
public class BaseDao {
private static String driver; //数据库驱动字符串
private static String url; //连接URL字符串
private static String user; //数据库用户名
private static String pwd; //用户密码
static{
init();
}
/**
* 从配置文件中读取连接参数
*/
public static void init(){
Properties params = new Properties();
String configfile = "database.properties";
//加载输入流
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configfile);
//从流中读取属性列表
try {
params.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//根据指定的键获取相应的值
driver = params.getProperty("driver");
url = params.getProperty("url");
user = params.getProperty("user");
pwd = params.getProperty("pwd");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
News news = new News();
//数据连接对象
/**
* 获取数据库连接对象
* @return
*/
public Connection getConnection(){
if (conn==null) {
//获取连接并捕获异常
try {
Class.forName(driver);//路径
conn = DriverManager.getConnection(url,user,pwd);
System.out.println("成功连接数据库!");
} catch (Exception e) { //异常处理
System.out.println(e);
}
}
return conn; //返回处理对象
}
public void closeAll(Connection conn,Statement stmt,ResultSet rs){
try {
//若结果集对象不为空,则关闭
if(rs != null){
rs.close();
}
//若Statement对象不为空,则关闭
if(stmt != null){
stmt.close();
}
//若数据库连接对象不为空,则关闭
if(conn != null){
conn.close();
}
System.out.println("成功关闭数据库!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<News> Select(String sql){
List<News> list = new ArrayList<News>();
conn=getConnection();
try {
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
news.setId(rs.getInt("Id"));
news.setTitle(rs.getString("title"));
news.setAuthor(rs.getString("author"));
news.setCreateTime(rs.getString("createTime"));
news.setContent(rs.getString("content"));
list.add(news);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeAll(conn,pstmt,rs);
}
return list;
}
}
评论0
最新资源