JDBC连接数据库

JDBC连接数据库的操作

1.JDBC数据库连接的几大要素

  • JDBC URL的标准由三部分组成,各部分之间用冒号分割
  • 格式:

    jdbc:<子协议>:<子名称>
    
    • 协议: JDBC URL中的协议总是jdbc
    • 子协议:子协议用于标识一个数据库驱动程序
    • 子名称:一种标识数据库的方法。子名称可以依不同的子协议而变化,用子名称的目的是为了定位数据库提供足够的信息
  • 几种常用数据库的JDBC URL:
    • Oracle数据库:
      • jdbc:oracle:thin:@localhost:1521:orcl(数据库名,一般默认为orcl)
    • SQL Server数据库:
      • jdbc:Microsoft:sqlserver//localhost:1433:DatabaseName=sid(数据库名)
    • MySQL数据库:
      • jdbc:mysql://localhost://3306/sid(数据库名)
      • :1521、1433、3306表示的是数据库的监听端口号

2.利用基本的Driver连接数据库

  • 单一连接固定数据库:

    public void tes1t() {
        try {
            //1.创建Driver实现类的对象
            Driver driver = new com.mysql.jdbc.Driver();
            System.out.println(driver);
            //2.创建连接数据库的内容(用户名、密码)对象
            Properties properties = new Properties();
            //3.设置数据库地址
            String url = "jdbc:mysql://127.0.0.1:3306/company";
            //3.向对象中 插入数据库登陆的用户名与密码
            properties.put("user", "root");
            properties.put("password", "java123");
            //4.通过驱动获取数据库连接对象
            Connection coon = driver.connect(url, properties);
            System.out.println(coon);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    • 运行结果如图:

      单一模式连接数据库

  • 通过反射机制动态获取数据库驱动

    • 配置文件:my.properties

      driverClass=com.mysql.jdbc.Driver
      jdbcUrl=jdbc:mysql://localhost:3306/java
      user=root
      password=java123
      //注意:在properties文件中,注释是以#号开头的,在这里使用了//
      //driverClass=oracle.jdbc.driver.OracleDriver
      //jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
      //user=scott
      //password=java123
      
    • 测试案例:

      public void test3() throws Exception{
          String driverName;
          String jdbcUrl;
          String user;
          String password;
      
          //1.获取当前类对象下的文件
          InputStream is = getClass().getClassLoader().getResourceAsStream("my.properties");
          Properties ps = new Properties();
          ps.load(is);
          //3.获取响应的文件内容
          driverName = ps.getProperty("driverClass");
          jdbcUrl = ps.getProperty("jdbcUrl");
          user = ps.getProperty("user");
          password = ps.getProperty("password");
          //调用方法返回连接数据库对象
          Connection coo = getConnection(driverName, jdbcUrl, user, password);
          System.out.println(coo);
          }
      
      //获取数据库连接方法
          public Connection getConnection(String driverName, String driverPath, String name, String pwd){
          Connection connection = null;
          try {
              //1.通过反射机制获取Driver实现类的对象
              @SuppressWarnings("static-access")
              Driver driver = (Driver)getClass().forName(driverName).newInstance();
              Properties info = new Properties();
              info.put("user", name);
              info.put("password", pwd);
              //2.获取数据库连接对象
              connection = driver.connect(driverPath, info);
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          return connection;
      }
      
    • 连接两种数据库的结果分别如下图所示:仅改变配置文件(.properties)即可

      • 连接MySQL数据库

        反射机制连接MySQL数据库

      • 连接Oracle数据库

        反射机制连接Oracle数据库

3.JDBC连接数据库并通过PreparedStatement(Statement)实现对象执行数据库操作

  • 使用PreparedStatement可以有效避免数据库操作中字符串拼接引起的注入问题
  • 使用PreparedStatement可以有效优化代码
  • 如下所采用的就是一个连接MySQL数据库并操作数据库的案例,采用的是面向对象(Java Bean)的形式来操纵数据库,如:

    • Java Bean:customer.class

      package com.ajb.statement;
      /**
       * Java Bean 对象
       * @author duanjunhua
       *
       */
      public class Customer {
          private String name;
          private String password;
          private int id;
      
          public int getId() {
              return id;
          }
          public void setId(int id) {
              this.id = id;
          }
          public String getName() {
              return name;
          }
          public void setName(String name) {
              this.name = name;
          }
          public String getPassword() {
              return password;
          }
          public void setPassword(String password) {
              this.password = password;
          }
      }
      
    • 主类:TestPreparedStatement.class

      package com.ajb.statement;
      import java.io.InputStream;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.util.Properties;
      import java.util.Scanner;
      import org.junit.Test;
      public class TestPreparedStatement {
          Connection coon = null;
          PreparedStatement pStatement = null;
          private boolean flag;
          private Customer customer;
          private String sql;
          private int Id;
      
          @Test
          public void test(){
              //1.获取Java Bean对象
              customer = getCustomer();
              //2.创建SQL语句
              if(customer == null)
                  return;
              else{
                  //PreparedStatement使用占位符的形式
                  if(customer.getId()==1){
                      sql = "insert into customer values(?, ?)";
                  }else if(customer.getId() == 2){
                      sql = "select * from customer where name=? and password=?";
                  }
              }
              //3.获取数据库连接对象
              coon = getConnection();
              //表若不存在则创建表
              if(tableExists(coon) == false){
                  createTable(coon);
              }
              //4.执行SQL语句操作
              executeSQL(coon, sql, customer);
              //5.释放连接(必须手动释放)
              release(coon, pStatement);
          }
      
          //判断数据库表是否存在
          public boolean tableExists(Connection connection){
              flag = false;
              String sqlquery = "select table_name from information_schema.tables";
              try {
                  pStatement = connection.prepareStatement(sqlquery);
                  ResultSet resultSet = pStatement.executeQuery();
                  while (resultSet.next()) {
                      if(resultSet.getString(1).equals("customer")){
                          flag = true;
                          return flag;
                      }
                  }
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return flag;
          }
          //创建表
          public void createTable(Connection connection){
              String sql = "create table customer("
                      + "name varchar(15),"
                      + "password varchar(15)"
                      + ")";
              try {
                  //获取PreparedStatement对象
                  pStatement = connection.prepareStatement(sql);
                  pStatement.executeUpdate();
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
          //从键盘输入获取Java Bean对象数据
          public Customer getCustomer(){
              Customer customer = new Customer();
              Scanner scanner = new Scanner(System.in);
              System.out.println("请选择模式:1、注册用户\n\t  2.用户登录");
              customer.setId(scanner.nextInt());
              //如果是两者之外的其他模式,直接退出并提示用户信息
              if(customer.getId()!= 1 && customer.getId() != 2){
                  System.out.println("选择错误,请重新运行输入...");
                  return null;
              }
              System.out.print("请输入用户名:");
              customer.setName(scanner.next());
              System.out.print("请输入登录密码:");
              customer.setPassword(scanner.next());
              return customer;
          }
          //获取数据库的配置文件
          //根据配置文件获取对应的数据库连接对象
          public Connection getConnection(){
              //
              Properties ps = new Properties();
              try {
                  InputStream is = getClass().getClassLoader().getResourceAsStream("my.properties");
                  ps.load(is);
                  coon = DriverManager.getConnection(ps.getProperty("jdbcUrl"), ps.getProperty("user"), ps.getProperty("password"));
              } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return coon;
          }
          //执行数据库的更新操作
          public void executeSQL(Connection connection, String sql, Customer customer){
              try {
                  //4.由连接对象获取PreparedStatement对象
                  pStatement = connection.prepareStatement(sql);
                  //5.加载数据
                  if(customer.getId() == 1){
                      if(TestPreparedStatement.queryUser(connection,customer) == false){
                          TestPreparedStatement.update(pStatement, customer.getName(), customer.getPassword());
                          pStatement.executeUpdate();
                      }else {
                          System.out.println("用户名已存在,请重新输入用户名!!!");
                          return;
                      }
                  }else {
                      TestPreparedStatement.update(pStatement, customer.getName(), customer.getPassword());
                      ResultSet resultSet = pStatement.executeQuery();
                      while(resultSet.next()){
                          System.out.println("登录成功 !!!");
                          return;
                      }
                      System.out.println("用户名或密码错误,请重新登录!!!");
                  }
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
          //使用setXxx()方法填充占位符
          public static void update(PreparedStatement pStatement, Object ... objects) throws SQLException{
              for(int i = 0; i < objects.length; i++){
                  pStatement.setObject(i + 1, objects[i]);
              }
          }
          //6.关闭数据库连接
          public static void release(Connection connection, PreparedStatement pStatement){
              if(pStatement != null){
                  try {
                      pStatement.close();
                  } catch (SQLException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
      
              if(connection != null){
                  try {
                      connection.close();
                  } catch (SQLException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
          }
      
          //查询用户名是否存在
          public static boolean queryUser(Connection connection,Customer customer){
              //Statement使用字符串拼接的形式
              String sql = "select name from customer where name= '" + customer.getName() + "'";
              try {
                  Statement statement = connection.createStatement();
                  ResultSet resultSet = statement.executeQuery(sql);
                  while (resultSet.next()) {
                      return true;
                  }
              } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return false;
          }
      }
      
    • 首次注册时同时创建数据库

      首次注册时同时创建数据库

    • 注册失败

      这里写图片描述

    • 登录成功

      用户名与密码正确时方可登录成功

    • 登录失败

      登录失败

    • 数据库

      数据库

注意:在进行与数据库连接的操作时需要有相应的数据库驱动,如图所示:

  • 工程目录

    工程目录

  • 在工程目录下新建lib文件夹,将相应的驱动.jar文件复制到该目录下
  • 通过选中右键Build Path -> Add to Build Path使之在Referenced Libraries目录下添加到工程目录库文件中以便调用

猜你喜欢

转载自blog.csdn.net/djh_happy/article/details/51250344