1. 程式人生 > >數據訪問類BaseDao實現

數據訪問類BaseDao實現

字符串 rom 用例 dstat lec 訪問 關閉 lean pos

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BaseDao {
	private String driver = "com.mysql.jdbc.Driver";
	private String db_URL = "jdbc:mysql://localhost:3306/netorder";
	private String username = "root";
	private String password = "*******";
	
	private Connection conn = null;
	
	public void openConnection() {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(db_URL,username,password);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
	public int executeUpdate(String sql,Object[] objs) {
		int res = -1;
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			if(objs != null) {
				for(int i = 0; i < objs.length; i++) {
					pst.setObject(i + 1, objs[i]);
				}
			}
			res = pst.executeUpdate();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public ResultSet executeQuery(String sql,Object[] objs) {
		ResultSet rs = null;
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			if(objs != null) {
				for(int i = 0; i < objs.length; i++) {
					pst.setObject(i + 1, objs[i]);
				}
			}
			rs = pst.executeQuery();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	public void close() {
		try {
			conn.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

}

使用方法:以user表為例

1.讓UserDao繼承BaseDao 

2.openConnection();//實例化數據庫連接

3.執行executeQuery()實現查詢或者執行excuteUpdate實現增刪改

4.close();//關閉數據庫連接

PS:支持預處理,可在sql字符串中加入?表示待定,使用例子如下:

public boolean checkUser(String username,String password) {
		openConnection();
		String sql = "select id from user where username = ? and password = ?";
		Object[] objs = new Object[]{username,password};
		ResultSet rs = executeQuery(sql, objs);
		close();
		if(rs != null) return true;
		else return false;
	}

  

數據訪問類BaseDao實現