JDBC訪問數據庫BaseDao工具類

配置文件:


工具類:

package day01_entity_dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class BaseDao {
	//數據庫加載驅動
	private static String driver;
	//數據庫連接字符串
	private static String url;
	//數據庫用戶名
	private static String user;
	//數據庫密碼
	private static String pwd;
	static
	{
		info();
	}
	/**
	 * 從配置文件中讀取鏈接參數
	 */
	public static void info()
	{
		Properties ties=new Properties();
		String config="database.properties";
		//加載配置文件到輸入流
		InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(config);
		//從輸入流中讀取屬性列表
		try {
			ties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//根據指定的鍵獲取對應的值
		driver=ties.getProperty("driver");
		url=ties.getProperty("url");
		user=ties.getProperty("user");
		pwd=ties.getProperty("password");
	}	
	//聲明連接對象
	private Connection con=null;
	/**
	 * 打開數據庫連接
	 * @return
	 */
	public Connection getConnection()
	{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con=DriverManager.getConnection(url,user,pwd);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
	/**
	 * 關閉連接對象
	 */
	public void closeAll(Connection con,PreparedStatement ment,ResultSet set)
	{
		if(set!=null)
		{
			try {
				set.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ment!=null)
		{
			try {
				ment.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(con!=null)
		{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 增刪改通用方法
	 */
	public int executeUpdate(String sql,Object[] obj)
	{
		int nums=0;//影響行數
		con=this.getConnection();//連接數據庫
		PreparedStatement stmt=null;//向數據庫發送sql語句
		try {
			stmt=con.prepareStatement(sql);
			//爲參數賦值
			if(obj!=null)
			{
				for (int i = 0; i < obj.length; i++) {
					stmt.setObject((i+1), obj[i]);
				}
			}
			//執行sql語句
			nums=stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally
		{
			//關閉連接
			this.closeAll(con, stmt, null);
		}
		return nums;
	}
	/**
	 * 讀取數據
	 */
	public ResultSet set(String sql,Object[] obj)
	{
		ResultSet result=null;//定義儲存容器
		PreparedStatement stmt=null;//向數據庫發送sql語句
		con=this.getConnection();//連接數據庫
		try {
			stmt=con.prepareStatement(sql);
			if(obj!=null)
			{
				for (int i = 0; i < obj.length; i++) {
					stmt.setObject((i+1), obj[i]);
				}
			}
			result=stmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章