JDBC使用DAO工厂模式

userDaoClass=com.ceit.dao.impl
#userDaoClass=cn.itcast.jdbc.dao.impl.UserDaoHibernateImpl
key=value
key1=value1

package com.ceit.dao;

import java.sql.SQLException;

import com.ceit.domain.student;

public interface UserDao {
	public void addUser(student stu) throws SQLException;

	public student findUser(String loginName,String password) throws DaoException;


	public void update(student stu) throws DaoException;

	public void delete(student stu) throws DaoException;
}

package com.ceit.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.ceit.dao.DaoException;
import com.ceit.dao.JdbcUtils;
import com.ceit.dao.UserDao;
import com.ceit.domain.student;
import com.mysql.jdbc.*;

public class UserDaoImpl implements UserDao {

	@Override
	public void addUser(student stu) throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			conn = (Connection) JdbcUtils.getConnection();
			String sql = "insert into student(name,school,phone) values(?,?,?)";
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps.setString(1,stu.getName());
			ps.setString(2, stu.getSchool());
			ps.setString(3, stu.getPhone());
			
			ps.executeUpdate();
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}finally{
			JdbcUtils.free(rs,ps,conn);
		}
	}

	@Override
	public student findUser(String loginName,String password) throws DaoException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		student stu = new student();
		try{
			conn = (Connection) JdbcUtils.getConnection();
			String sql = "select id,name,school,phone,sex,project,courseid from student where name=?";
			
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps.setString(1,loginName);
			rs = ps.executeQuery();
			while(rs.next()){
				
				mappingStu(rs, stu);
				
			}
			
			
		}
		catch(SQLException e){
			throw new DaoException(e.getMessage(),e);
		}finally{
			JdbcUtils.free(rs,ps,conn);
		}
		return stu;
	}
	
	public student getstudent(int stuId) throws DaoException{
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		student stu = new student();
		try{
			conn = (Connection) JdbcUtils.getConnection();
			String sql = "select id,name,school,phone,sex,project,courseid from student where id=?";
			
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps.setLong(1,stuId);
			rs = ps.executeQuery();
			while(rs.next()){
				
				mappingStu(rs, stu);
				
			}
			
			
		}
		catch(SQLException e){
			throw new DaoException(e.getMessage(),e);
		}finally{
			JdbcUtils.free(rs,ps,conn);
		}
		return stu;
	}

	private void mappingStu(ResultSet rs, student stu) throws SQLException {
		stu.setId(rs.getInt("id"));
		stu.setName(rs.getString("name"));
		stu.setSchool(rs.getString("school"));
		stu.setPhone(rs.getString("phone"));
	}
	
	@Override
	public void update(student stu) throws DaoException {
		// TODO Auto-generated method stub
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		try{
			conn = (Connection) JdbcUtils.getConnection();
			String sql = "update student set name=?,school=?,phone=?,sex=? where id=?";
			
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps.setString(1,stu.getName());
			ps.setString(2,stu.getSchool());
			ps.setString(3,stu.getPhone());
			ps.setString(4,stu.getSex());
			ps.executeUpdate();
		}catch(SQLException e){
			throw new DaoException(e.getMessage(),e);
		}finally{
			JdbcUtils.free(rs,ps,conn);
		}
			
	}

	@Override
	public void delete(student stu) throws DaoException {
		// TODO Auto-generated method stub
				Connection conn = null;
				Statement st = null;
				ResultSet rs = null;
				try{
					conn = (Connection) JdbcUtils.getConnection();
					st = (Statement) conn.createStatement();
					String sql = "delete from user where id=" + stu.getId();
					st.executeUpdate(sql);
				}
				catch(SQLException e){
					throw new DaoException(e.getMessage(),e);
				}finally{
					JdbcUtils.free(rs,st,conn);
				}
		
	}

}

package com.ceit.domain;

import java.util.ArrayList;

import com.ceit.project.Project;

public class student {
	private String name;
	private long id;
	private String sex;
	private String school;
	private String phone;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getSchool() {
		return school;
	}
	public void setSchool(String school) {
		this.school = school;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public ArrayList<Project> getMyProject() {
		return myProject;
	}
	public void setMyProject(ArrayList<Project> myProject) {
		this.myProject = myProject;
	}
	public ArrayList<Course> getMyCourse() {
		return myCourse;
	}
	public void setMyCourse(ArrayList<Course> myCourse) {
		this.myCourse = myCourse;
	}
	private ArrayList<Project> myProject= new ArrayList<Project> ();
	private ArrayList<Course> myCourse= new ArrayList<Course> ();
	
}

package com.ceit.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;


public class DaoFactory {
	private static UserDao userDao = null;//置上 否则会为空
	private static DaoFactory instance = new DaoFactory();

	private DaoFactory() {
		try {
			Properties prop = new Properties();
			InputStream inStream = DaoFactory.class.getClassLoader()
					.getResourceAsStream("daoconfig.properties"); //类加载器
			prop.load(inStream);
			String userDaoClass = prop.getProperty("userDaoClass");
			Class clazz = Class.forName(userDaoClass);
			userDao = (UserDao) clazz.newInstance();
		} catch (Throwable e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static DaoFactory getInstance() {
		return instance;
	}

	public UserDao getUserDao() {
		return userDao;
	}
}

package com.ceit.dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JdbcUtils {
    private static String user = "root";
    private static String password = "root";
    //private static String password = "541065";
    private static String url = "jdbc:mysql://localhost:3306/cooventure?useUnicode=true&characterEncoding=UTF-8";
    //private static String url = "jdbc:mysql://210.30.208.152:3306/teacherinfo?useUnicode=true&characterEncoding=UTF-8";
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    
    public static Connection getConnection() throws SQLException {
        Connection conn=DriverManager.getConnection(url, user, password);
       	return conn;
    }
    
    
    public static void executeSql(String sql){
    	Statement  stmt = null;
    	Connection conn = null;
    	try{
    		conn = getConnection();
    		stmt = conn.createStatement();
    		stmt.execute(sql);

    	}catch(SQLException e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if(stmt != null)
    				stmt.close();
    			if(conn != null){
    				conn.close();
    			}
    		}catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    }
    public static void executeDeleteSql(String sql){
    	Statement  stmt = null;
    	Connection conn = null;
    	try{
    		conn = getConnection();
    		stmt = conn.createStatement();
    		stmt.executeUpdate(sql);

    	}catch(SQLException e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if(stmt != null)
    				stmt.close();
    			if(conn != null){
    				conn.close();
    			}
    		}catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    }
    
    
    
    
    public static List<Map<String,Object>> executeQuery(String sql,String[] params){
    	/*String []params = null;*/
    	Connection conn = null;
    	Statement stmt = null;
		ResultSet rs = null;
  		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	try{
    		conn = getConnection();
    		stmt = conn.createStatement();
    		rs = stmt.executeQuery(sql);
    		/*ResultSetMetaData rsmd=rs.getMetaData();
    		int count=rsmd.getColumnCount();*/
    		/*while(rs.next()){
    			Map<String,Object> map = new  HashMap<String,Object>();
    		for(int i=0;i<count;i++){
    			params[i] = rsmd.getColumnName(i);//把列名存入向量heads中
    			}
    		list.add(map);
    		}*/
    		while(rs.next()){
    			Map<String,Object> map = new HashMap<String,Object>();
    			for(int i=0;i<params.length;i++){
    				map.put(params[i]+"", rs.getString(params[i]));    				
    			}
    			list.add(map);
    		}
    		
    	}catch(SQLException e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if(rs != null)
    				rs.close();
    			if(stmt != null)
    				stmt.close();
    			if(conn != null)
    				conn.close();
    		}catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    	return list;
    	
    }
    
    public static Connection beginSession(){
    	Connection conn = null;
    	try {
			conn = getConnection();
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return conn;
    }
    public static void executeSql(Connection conn,String sql){
    	Statement  stmt = null;  
    	try{
    		stmt = conn.createStatement();
    		stmt.execute(sql);
    	}catch(SQLException e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if(stmt != null)
    				stmt.close();
    		}catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    }
    
    public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}
}


你可能感兴趣的:(sql,jdbc,工厂模式)