Mysql

Mysql:jdbc初步

2019-04-14  本文已影响0人  蘑菇v5

【声明:】本文是作者(蘑菇v5)原创,版权归作者 蘑菇v5所有,侵权必究。本文首发在简书。如若转发,请注明作者和来源地址!未经授权,严禁私自转载!

简介:

数据库驱动:

数据库厂商为了方便开发人员从程序中操作数据库而提供的一套jar包,通过导入这个jar包就可以调用其中的方法操作数据库,这样的jar包就叫做数据库驱动,下载地址一般会在该数据库的官网,比如我们这里所说的MySql,那么mysql的驱动就在mysql的官网可以下载

JDBC:

sun定义的一套标准,本质上是一大堆的操作数据库的接口,所有数据库厂商为java设计的数据库驱动都实现过这套接口,这样一来统一了不同数据库驱动的方法,开发人员只需要学习JDBC就会使用任意数据库驱动了

原理
项目应用:
1、下载Mysql的connector:

connectorjar包加入到classpath

jar
2、注册数据库驱动,加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
3、获取数据库连接connection
 String username = "itat";
 String password = "itat123";
 String url = "jdbc:mysql://localhost:3306/itat_shop?
serverTimezone=UTC
&characterEncoding=utf-8&useSSL=false
&allowPublicKeyRetrieval=true";
 con = DriverManager.getConnection(url, username, password);
4、获取传输器对象,利用传输器对象执行sql语句,获取结果集对象
  String sql = "select count(*) from t_user where username=?";
  ps = con.prepareStatement(sql);
  ps.setString(1, user.getUsername());
  rs = ps.executeQuery();
5、遍历结果集获取查询结果
 while (rs.next()) {
                if (rs.getInt(1) > 0) {
                    throw new ShopException("添加的用户已经存在!不能继续添加");
                }
            }
6、关闭资源,释放连接

先释放resultSet,再释放prepareStatement,最后释放connection

finally {
     DBUtil.close(rs);
     DBUtil.close(ps);
     DBUtil.close(con);
 }

特别关注以下问题:

/**
 * 工厂模式
 */
public class DaoFactory {
    public static IUserDao getUserDao() {
        return new UserDao();//此处可以读取配置文件
    }
}

源码:

DBUtil :

public class DBUtil {

    public static Connection getConnection() {
        Connection con = null;
        String username = "itat";
        String password = "itat123";
        String url = "jdbc:mysql://localhost:3306/itat_shop?serverTimezone=UTC
        &characterEncoding=utf-8
        &useSSL=false
        &allowPublicKeyRetrieval=true";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static void close(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

init.sql:

drop database IF EXISTS itat_shop;
create database itat_shop;
use itat_shop;
create table t_user(
    id int(10) primary key auto_increment,
    username varchar(100),
    password varchar(100),
    nickname varchar(100),
    status int(3),
    type int(3)
);
GRANT ALL ON itat_shop.* to 'itat'@'localhost';

IUserDao:

public interface IUserDao {
    public void add (User user);
    public void deleta(int id);
    public void update(User user);
    public User load(int id);
    public List<User>list();
    public User login(String username,String password);
}

UserDao:

public class UserDao implements IUserDao {
    @Override
    public void add(User user) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = DBUtil.getConnection();
            String sql = "select count(*) from t_user where username=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getInt(1) > 0) {
                    throw new ShopException("添加的用户已经存在!不能继续添加");
                }
            }
            sql = "insert into t_user (username,password,nickname) 
              value (?,?,?)";
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs);
            DBUtil.close(ps);
            DBUtil.close(con);
        }
    }

    @Override
    public void deleta(int id) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = DBUtil.getConnection();
            String sql = "delete from t_user where id=?";
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(ps);
            DBUtil.close(con);
        }
    }

    @Override
    public void update(User user) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = DBUtil.getConnection();
            String sql = "update t_user set password=?,nickname=? where id=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getPassword());
            ps.setString(2, user.getNickname());
            ps.setInt(3, user.getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(ps);
            DBUtil.close(con);
        }
    }

    @Override
    public User load(int id) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User u = null;
        try {
            con = DBUtil.getConnection();
            String sql = "select * from t_user where id=?";
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {
                u = new User();
                u.setId(rs.getInt("id"));
                u.setNickname(rs.getString("nickname"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs);
            DBUtil.close(ps);
            DBUtil.close(con);
        }
        return u;
    }

    @Override
    public List<User> list() {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<User>();
        User u = null;
        try {
            con = DBUtil.getConnection();
            String sql = "select * from t_user";
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                u = new User();
                u.setId(rs.getInt("id"));
                u.setNickname(rs.getString("nickname"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));
                users.add(u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs);
            DBUtil.close(ps);
            DBUtil.close(con);
        }
        return users;
    }

    @Override
    public User login(String username, String password) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User u = null;
        try {
            con = DBUtil.getConnection();
            String sql = "select * from t_user where username=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            while (rs.next()) {
                u = new User();
                u.setId(rs.getInt("id"));
                u.setNickname(rs.getString("nickname"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));
            }
            if (u == null) throw new ShopException("用户名不存在!");
            if (!u.getPassword().equals(password))
           throw new ShopException("用户密码不正确!");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs);
            DBUtil.close(ps);
            DBUtil.close(con);
        }
        return u;
    }
}

add.jsp:

<%@ page import="itat.zttc.shop.model.User" %>
<%@ page import="itat.zttc.shop.dao.DaoFactory" %>
<%@ page import="itat.zttc.shop.dao.IUserDao" %>
<%@ page import="itat.zttc.shop.util.ValidateUtil" %><%--
  Created by IntelliJ IDEA.
  User: zsn10
  Date: 2018/10/19
  Time: 15:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String nickname = request.getParameter("nickname");
    boolean validate = ValidateUtil.validateNull(
      request, new String[]{"username", "password", "nickname"});
    if (!validate) {
%>
<jsp:forward page="addInput.jsp"/>
<%
    }

    User user = new User();
    user.setUsername(username);
    user.setPassword(password);
    user.setNickname(nickname);
    IUserDao userDao = DaoFactory.getUserDao();
    try {
        userDao.add(user);
        response.sendRedirect("list.jsp");
        return;
    } catch (Exception e) {
%>
<h2 style="color:red">发生错误:<%=e.getMessage()%>
</h2>
<%
    }
%>
上一篇下一篇

猜你喜欢

热点阅读