javaweb配置鏈接mysql數據庫

一、首先新建基礎鏈接類BaseDao,在這裏配置連接的數據庫名稱,用戶名以及密碼,以及執行讀與寫操做的父方法,代碼以下:java

package com.demo.dao;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 數據庫操做類
 * @author zhangdi
 *
 */

public class BaseDao {

    //數據庫地址「jdbc:mysql://服務器域名:端口號/數據庫名稱」
    private String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf-8";
    //用戶名
    private String user = "root";
    //用戶密碼
    private String pwd = "zhangdi";
    //數據庫連接對象
    private java.sql.Connection conn;
    //數據庫命令執行對象
    private PreparedStatement pstmt;
    //數據庫返回結果
    private java.sql.ResultSet rs;
    
    //靜態代碼塊
    static{
        //一、加載驅動
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            
            e.printStackTrace();
        }
    }
    
    //二、建立鏈接
    private void getConnection(){
        if(conn == null){
            try {
                conn = DriverManager.getConnection(url, user, pwd);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    //執行讀操做方法
    public java.sql.ResultSet executeQuery(String query,
                    List<Object> params){
        getConnection();
        try {
            //三、建立命令執行對象
            pstmt = conn.prepareStatement(query);
            //四、執行
            if(params!=null && params.size()>0){
                for(int i=0;i<params.size();i++){
                    pstmt.setObject(i+1, params.get(i));
                }
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    
    //執行寫操做方法
    public int executeUpdate(String query,
            List<Object> params){
        int result = 0;
        getConnection();
        try {
            //三、建立命令執行對象
            pstmt = conn.prepareStatement(query);
            //四、執行
            if(params!=null && params.size()>0){
                for(int i=0;i<params.size();i++){
                    pstmt.setObject(i+1, params.get(i));
                }
            }
            //五、處理結果
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //六、釋放資源
            this.close();
        }
        return result;
    }

    
    //關閉資源
    public void close(){        
            try {
                if(rs!=null){
                    rs.close();
                    rs = null;
                }
                if(pstmt!=null){
                    pstmt.close();
                    pstmt = null;
                }
                if(conn!=null){
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        
        }

}

二、第二步,就建立一個數據庫操做接口類,採用面向接口的開發思想以便於後期維護,代碼以下:mysql

package com.demo.dao;

import java.util.List;

import com.demo.entity.User;

public interface UserDao {
    public int addUser(User user);
    public List<User> findUsers();
    public List<User> findUsers(String name);
    public List<User> findUsersByDept(String dept);
    public List<User> findUsersByRole(String role);
    public int delUserById(int id);
    public int updateUserById(int id,User role);
    public boolean checkUser(String name);
}

三、第三步建立數據庫操做對象接口實現類並繼承數據庫操做基礎類:web

package com.demo.daoimpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.demo.dao.BaseDao;
import com.demo.dao.DeptDao;
import com.demo.dao.RoleDao;
import com.demo.dao.UserDao;
import com.demo.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao {
    DeptDao deptDao = new DeptDaoImpl();
    RoleDao roleDao = new RoleDaoImpl();
    //添加一條用戶信息
    @Override
    public int addUser(User user) {
        String update = "insert into users(account,pwd,NAME,dept,role,phone,qq,email,remark)values(?,?,?,?,?,?,?,?,?)";
        List<Object> params = new ArrayList<Object>();
        params.add(user.getAccount());
        params.add(user.getPwd());
        params.add(deptDao.returnDeptIdByName(user.getDept()));
        params.add(roleDao.returnRoleIdByName(user.getRole()));
        params.add(user.getRole());
        params.add(user.getPhone());
        params.add(user.getQq());
        params.add(user.getEmail());
        params.add(user.getMark());
        return this.executeUpdate(update, params);
    }

    @Override
    public List<User> findUsers() {
        List<User> result = new ArrayList<User>();
        String query = "select id,account,pwd,NAME,dept,role,phone,qq,email,remark from users";
        ResultSet rs = this.executeQuery(query, null);
        try {
            while(rs.next()){
                int id = rs.getInt("id");
                String account = rs.getString("account");
                String pwd = rs.getString("pwd");
                String name = rs.getString("NAME");
                String dept = deptDao.returnDeptNameById(rs.getInt("dept"));
                String role = roleDao.returnRoleNameById(rs.getInt("role"));
                String phone ="11";//+ rs.getInt("phone");
                String qq = "22";//+rs.getInt("qq");
                String email = rs.getString("email");
                String mark = rs.getString("remark");
                User user = new User(id, account,pwd,name,dept,role,phone,qq,email,mark);
                result.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
                this.close();
        }
        return result;
    }

    @Override
    public List<User> findUsersByDept(String dept) {
        List<User> result = new ArrayList<User>();
        List<Object> params = new ArrayList<Object>();
        String query = "select id,account,pwd,NAME,dept,role,phone,qq,email,remark from users where dept =?";
        if(dept!=null&&!"".equals(dept)){
            int d = deptDao.returnDeptIdByName(dept);
            params.add(d);
        }
        ResultSet rs = this.executeQuery(query, params);
        try {
            while(rs.next()){
                int id = rs.getInt("id");
                String account = rs.getString("account");
                String pwd = rs.getString("pwd");
                String name = rs.getString("NAME");
                String deptName = deptDao.returnDeptNameById(rs.getInt("dept"));
                String role = roleDao.returnRoleNameById(rs.getInt("role"));
                String phone = Integer.toString(rs.getInt("phone"));
                String qq = Integer.toString(rs.getInt("qq"));
                String email = rs.getString("email");
                String mark = rs.getString("remark");
                User user = new User(id, account,pwd,name,deptName,role,phone,qq,email,mark);
                result.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
                this.close();
        }
        return result;
    }

    @Override
    public List<User> findUsersByRole(String role) {
        List<User> result = new ArrayList<User>();
        List<Object> params = new ArrayList<Object>();
        String query = "select id,account,pwd,NAME,dept,role,phone,qq,email,remark from users where role =?";
        if(role!=null&&!"".equals(role)){
            int d = roleDao.returnRoleIdByName(role);
            params.add(d);
        }
        ResultSet rs = this.executeQuery(query, params);
        try {
            while(rs.next()){
                int id = rs.getInt("id");
                String account = rs.getString("account");
                String pwd = rs.getString("pwd");
                String name = rs.getString("NAME");
                String deptName = deptDao.returnDeptNameById(rs.getInt("dept"));
                String roleName = roleDao.returnRoleNameById(rs.getInt("role"));
                String phone = Integer.toString(rs.getInt("phone"));
                String qq = Integer.toString(rs.getInt("qq"));
                String email = rs.getString("email");
                String mark = rs.getString("remark");
                User user = new User(id, account,pwd,name,deptName,roleName,phone,qq,email,mark);
                result.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
                this.close();
        }
        return result;
    }

    @Override
    public int delUserById(int id) {
        String query = "delete from users where id = ?";
        List<Object> params = new ArrayList<Object>();
        params.add(id);
        return this.executeUpdate(query, params);
    }

    @Override
    public int updateUserById(int id, User role) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public boolean checkUser(String name) {
        List<User> list = new ArrayList<User>();
        list = this.findUsers();
        for(User u:list){
            if(u.getName().equals(name)){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<User> findUsers(String name) {
        List<User> result = new ArrayList<User>();
        List<Object> params = new ArrayList<Object>();
        String query = "select id,account,pwd,NAME,dept,role,phone,qq,email,remark from users where 1=1";
        if(name!=null&&!"".equals(name)){
            query = query+" and NAME like ?";
            params.add("%"+name+"%");
        }
        ResultSet rs = this.executeQuery(query, params);
        try {
            while(rs.next()){
                int id = rs.getInt("id");
                String n = rs.getString("name");
                String desc = rs.getString("desc");
                User user = new User();
                result.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
                this.close();
        }
        return result;
    }

}

這裏面role與dept也是兩個數據庫操做類,你們能夠忽略,其中User爲實體類,代碼以下:sql

package com.demo.entity;

public class User {
    private int id;
    private String account;
    private String pwd;
    private String name;
    private String dept;
    private String role;
    private String phone;
    private String qq;
    private String mark;
    private String email;
    
    
    
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAccount() {
        return account;
    }
    public void setAccount(String account) {
        this.account = account;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getQq() {
        return qq;
    }
    public void setQq(String qq) {
        this.qq = qq;
    }
    public String getMark() {
        return mark;
    }
    public void setMark(String mark) {
        this.mark = mark;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(int id, String account, String pwd, String name, String dept,
            String role, String phone, String qq, String mark, String email) {
        super();
        this.id = id;
        this.account = account;
        this.pwd = pwd;
        this.name = name;
        this.dept = dept;
        this.role = role;
        this.phone = phone;
        this.qq = qq;
        this.mark = mark;
        this.email = email;
    }
    public User(String account, String pwd, String name,int id) {
        super();
        this.account = account;
        this.pwd = pwd;
        this.name = name;
        this.id = id;
    }
    
}

至此,web後臺與mysql數據庫的連接就完成了,若是要執行對數據庫的操做就調用數據庫操做類便可。數據庫

注:這裏須要引用的jar包爲:服務器

這些爲項目基礎jar包:ide

相關文章
相關標籤/搜索