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

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

7.预处理的原理

服务器工作:

(1)校验:sql语句的语法

(2)编译:为一个与函数相似的东西

(3)执行:调用函数

PreparedStatement

(1)先将sql发给数据库,数据库先进行校验

(2)执行的时候只发送参数

8.mysql的预编译功能默认是关闭的

prepare myfun from 'select * from student where sid = ?'
set @uid=1
execute myfun using @uid

设置连接参数:

useServerPrepStmts=true

cachePrepStmts=true

DB_URL = "jdbc:mysql://localhost:3306/data?useServerPrepStmts=true&cachePrepStmts=true";

9.JdbcUtils1.0小工具

JdbcUtils.java

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

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

  private static Properties prop = null;

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

    // 加载驱动
    try{
      Class.forName(prop.getProperty("driver"));
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

  public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(
        prop.getProperty("url"),
        prop.getProperty("username"),
        prop.getProperty("password")
    );
  }

  public static void main(String[] args) throws SQLException {
    Connection conn = getConnection();
    System.out.println(conn);
  }

}

dbconfig.properties

driver=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://localhost:3306/data

username=root

password=123456

10.面向接口编程

DAO模式

data access object

写一个类,把访问数据库的代码封装起来

DAO在数据库与业务逻辑(service)之间

实体域,即操作的对象

DAO模式步骤

(1)提供一个DAO接口

(2)提供一个DAO接口的实现类

(3)在编写一个DAO工厂,Service通过工厂来获取DAO实现

daoconfig.properties

UserDaoClassName=UserDaoImpl

UserDao.java

public interface UserDao {
}

UserDaoImpl.java

public class UserDaoImpl implements UserDao{

}

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);
    }
  }

}