java数据库开发之JDBC基础使用方法及实例详解

2020-02-19 12:01:55王冬梅

11.修改案例,其中dao层为jdbc

User.java

public class User {
  private String username;
  private int age;

  public String getUsername() {
    return username;
  }

  public int getAge() {
    return age;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "User{" +
        "username='" + username + ''' +
        ", age=" + age +
        '}';
  }
}

daoconfig.properties

UserDaoClassName=UserDaoImpl

UserDao.java

public interface UserDao {
  public void addUser(User user);
  public User getUserByUsername(String username);
}

UserDaoImpl.java

import util.JdbcUtils;

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

/**
 * create table user(
 * id int primary key auto_increment,
 * username varchar(50),
 * age int
 * )
 */
public class UserDaoImpl implements UserDao {

  /**
   * ORM 对象关系映射
   * @param user
   */
  @Override
  public void addUser(User user) {
    Connection conn = null;
    PreparedStatement statement = null;

    try {
      // 得到连接
      conn = JdbcUtils.getConnection();
      String sql = "insert into user(username, age) values(?, ?)";

      // 准备模板
      statement = conn.prepareStatement(sql);

      // 赋值
      statement.setString(1, user.getUsername());
      statement.setInt(2, user.getAge());

      // 执行
      statement.executeUpdate();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (statement != null) {
          statement.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (SQLException e) {

      }
    }
  }

  @Override
  public User getUserByUsername(String username) {

    Connection conn = null;
    PreparedStatement statement = null;

    try {
      // 得到连接
      conn = JdbcUtils.getConnection();
      String sql = "select * from user where username = ? limit 1";

      // 准备模板
      statement = conn.prepareStatement(sql);

      // 赋值
      statement.setString(1, username);

      // 执行
      ResultSet resultSet = statement.executeQuery();
      if(resultSet.next()){
        User user = new User();
        user.setUsername(resultSet.getString("username"));
        user.setAge(resultSet.getInt("age"));
        return user;
      }
      else{
        return null;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (statement != null) {
          statement.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (SQLException e) {

      }
    }
  }
}

DaoFactory.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class DaoFactory {
  // 配置文件路径
  private static String dbconfig = "daoconfig.properties";

  private static Properties prop = null;

  // 静态代码块只执行一次
  static {
    // 初始化数据库配置参数
    try {
      InputStream in = DaoFactory.class.getClassLoader().getResourceAsStream(dbconfig);
      prop = new Properties();
      prop.load(in);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 返回一个UserDao的具体实现类
   */
  public static UserDao getUserDao() {
    String daoClassName = prop.getProperty("UserDaoClassName");

    // 通过反射创建实现类的对象
    try {
      Class Clazz = Class.forName(daoClassName);
      return (UserDao) Clazz.newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

}