Java_Jdbc

目录

一.JDBC概述

二.JDBC API

三.ResultSet[结果集]

四.Statement 

 五.PreparedStatement

六. JDBC API 总结


一.JDBC概述

  1. JDBC 为访问不同的数据库提供了同一的接口,为使用着屏蔽了细节问题
  2. Java程序员使用JDBC 可以连接任何提供了  JDBC驱动的数据库系统,从而完成对数据库的各种操作
  3. JDKC的原理图
  4. 模拟JDBC  com.hspedy.jdbc.myjdbc

JDBC是java操作提供的一套用于数据库操作的接口API,java程序员只需要面向这套接口编程计科。不同的数据库厂商,需要针对这套接口,提供不同实现。

二.JDBC API

JDBC API 是一系列接口,她同一和规范了应用程序于数据的连接,执行SQL语句,并得到返回结果等各种操作,相关类和接口在java.sql与 javax.sql 包中 

 JDBC程序编写步骤

  1. 注册驱动   加载Driver类
  2. 获取连接  得到 connection
  3. 执行增删改查 发送相关的sql命令给mysql执行
  4. 释放资源    关闭相关的连接等

package com.tianedu.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author tian
 * 这是第一个JDBC程序 完成简单的操作
 */
public class Jdbc01 {
    public static void main(String[] args) throws SQLException {
        // 前置工作在项目下创建一个文件夹 libs
        // 将 mysql.jar 拷贝到该目录下,点击 add to project 加入到项目中才可以使用

        //1.注册驱动
        Driver driver = new Driver();  // 创建driver 对象
        //2.得到连接
        //(1)  jdbc: // 规定好的协议,通过jdbc的方式连接mysql
        //(2)  localhost 主机,也可以是ip地址
        //(3) 3306 表示MySQL 监听的端口
        //(4) hsp_db03 表示连接到呢个数据库
        // (5) MySQL的连接本质就是前面学习过sql 的连接
        String url = "jdbc:mysql://localhost:3306/hsp_db03";
        // 将用户名和密码 放到Properties 对象中
        Properties properties = new Properties();
        // 说明: user 和 password 是规定好的,后面的值根据实际情况写
        properties.setProperty("user","root"); // 用户
        properties.setProperty("password","tian"); //密码

        Connection connect = driver.connect(url, properties);
        //3.执行sql语句
        //String sql = "insert into actor values(null,'刘德华','男','1970-11-11',110)";
        // String sql = "update actor set name = '周星驰'where id = 1";
        String sql = "delete from actor where id = 1";
        // 下面的statement 用于执行静态的sql 语句并返回其生成的结果的对象
        Statement statement = connect.createStatement();
        int rows =  statement.executeUpdate(sql);  // 如果是dml语句,返回的就是影响行数 如果是1 添加成功 如果是0 添加失败
        System.out.println(rows > 0 ? "成功":"失败");
        //4.关闭资源
        statement.close();
        connect.close();
    }
}

获取数据库连接5种方式

package com.tianedu.jdbc;

import com.mysql.jdbc.Driver;
import org.junit.Test;

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

/**
 * @author tian
 * 分析java 连接MySQL的物种方式
 */
public class JdbcConn {
    @Test
    public void connect01() throws SQLException {
        Driver driver = new Driver();
        String url = "jdbc:mysql://localhost:3306/hsp_db03";
        // 将用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "tian");
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }
    //方式2
    @Test
    public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        //使用反射加载Driver 动态加载,更加灵活,减少依赖性
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver)aClass.newInstance();
        String url = "jdbc:mysql://localhost:3306/hsp_db03";
        // 将用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "tian");

        Connection connect = driver.connect(url, properties);
        System.out.println("方式2=" + connect);
    }
    // 方式3 使用DriverManager 替代 Driver 进行统一管理
    @Test
    public void connect03() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
        // 使用反射 加载Driver
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver  = (Driver) aClass.newInstance();
        //创建 url 和 user 和 password
        String url = "jdbc:mysql://localhost:3306/hsp_db03";
        String user = "root";
        String password = "tian";
        DriverManager.registerDriver(driver);  //注册Driver 驱动
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println("第三种方式" + connection);
    }
    // 方式4   使用Class.forName 自动完成注册,简化代码
    // 使用最多
    @Test
    public void  connect04() throws ClassNotFoundException, SQLException {
       // 使用反射加载 Driver 类
        // 在加载Driver类时,完成注册
        /*
            源码: 1.静态代码块,在类加载时,会执行一次
            2.DriverManager.registerDriver(new Driver());
            3.因此 加载和注册Driver 的工作已经完成
            static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
         */

        Class.forName("com.mysql.jdbc.Driver") ;  //如果没有这句也可以执行,建议写上更加明确
        // MySQL 驱动 5.1.6 可以无需Class.forName("com.mysql.jdbc.Driver");
        // 从 jdk1.5 以后使用Jdbc4 不在需要显示调用class.forName() 注册驱动而已自动调用驱动
        // jar包下META-INF\services\java.sql.Driver文本种的类 名称去注册
        String url = "jdbc:mysql://localhost:3306/hsp_db03";
        String user = "root";
        String password = "tian";
        Connection connection = DriverManager.getConnection(url,user,password);
        System.out.println("第四种方式" + connection);
    }
    @Test
    // 方式5,在方式4的基础上改进,增加配置文件,让信息连接MySQL更加灵活
    public void connect05() throws IOException, ClassNotFoundException, SQLException {
        //通过Properties 对象获取配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        Class.forName(driver); //建议写上 更加明确
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println("方式5" + connection);
    }
}

三.ResultSet[结果集]

  1. 表示数据库结果的数据表,通常通过执行查询数据库的语言生成
  2. ResultSet对象保持一个光标指向其当中的数据行,最初,给光标位于第一行之间
  3. next方法将光标移动到下一行,并且由于在ResultSet对象种没有更多行时返回false,因此可以在while 循环中使用循环来遍历结果集
package com.tianedu.jdbc.resultest_;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author tian
 *
 * 演示select 语句返回一个resultset 并取出结果
 */
@SuppressWarnings({"all"})
public class ResultSet_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        //通过Properties 对象获取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        Class.forName(driver); //建议写上 更加明确
        Connection connection = DriverManager.getConnection(url, user, password);
        //得到Statement
        Statement statement = connection.createStatement();
        //组织sql 语句
        String sql = "select id,name,sex,borndate from actor";
        //执行给定的sql语句,该语句返回单个 ResultSet对象
        ResultSet resultSet = statement.executeQuery(sql);
        // 使用where 循环取出数据
        while (resultSet.next()) {
            // 让光标向后移动 如果没有更多的记录则返回false
       int id =  resultSet.getInt(1);
            String name = resultSet.getString(2);// 获取该行第二列
            String sex = resultSet.getString(3);
            Date date = resultSet.getDate(4);
            System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
            // 获取该行的对第一列
        }
        // 关闭连接
        resultSet.close();
        connection.close();
        statement.close();

    }
}

四.Statement 

  1. statement 对象 用于执行静态SQL语句返回生成的结果的对象
  2. 在连接建立后,需要对数据库进行访问,执行命令或是sql 语句,可以通过 Statement【存在sql注入】,PerparedStatement【预处理】,CallableStatement【存储过程】
  3. Statement对象执行sql语句,存在sql 注入风险
  4. sql 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的sql 语句或命令,恶意攻击数据库。sql_injection.sql
  5. 要防范sql注入,只要用PerparedStatement(从Statement 扩展而来)取代Statement 就可以了
package com.tianedu.jdbc.statement_;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author tian
 * 演示statement 的注入问题
 */
@SuppressWarnings({"all"})
public class Statement_ {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        //让用户输入管理员姓名和密码
        System.out.print("请输入管理员的名字:");
        String admin_name = scanner.nextLine(); //next当接受到空格或者 ' 表示结束
        System.out.print("请输入管理员的密码:");
        String admin_pwd = scanner.nextLine();
        // 通过Properties 对象获取配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        //1.注册驱动
        Class.forName(driver);

        //2.得到连接
        Connection connection = DriverManager.getConnection(url,user,password);
        //3.得到Statement
        Statement statement = connection.createStatement();
        //4.组织sql
        String sql = "select name,pwd from admin where name = '"
                +admin_name+"' and pwd= '"+admin_pwd+"'" ;
        ResultSet resultSet = statement.executeQuery(sql);
        if(resultSet.next()){
            //如果查询到一条记录,则说明该管理员存在
            System.out.println("登录成功");
        } else  {
            System.out.println("对不起,登录失败");
        }
        // 关闭连接
        resultSet.close();
        statement.close();
        connection.close();
    }

}

 五.PreparedStatement

  1. PreparedStatement 执行的sql语句中的参数用问号(?)来表示,调用PerparedStatement 对象的setXxxx() 方法来设置这些参数。setXxx() 方法有两个参数,第一个参数是要设置的sql语句中的索引(从1开始),第二个是设置的sql 语句中的参数值
  2. 调用 executeQuery() 返回ResultSet 对象
  3. 调用 executeUpdate(): 执行更新,包括增,删,修改

 预处理好处

  1. 不在使用 + 拼接sql语句,减少语法错误
  2. 有效的解决了sql注入问题
  3. 大大减少了编译次数,效率较高
package com.tianedu.jdbc.preparedstatement_;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author tian
 *
 * 演示 preparedStatement使用
 */
@SuppressWarnings({"all"})
public class PreparedStatementDML_ {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        //让用户输入管理员姓名和密码
        System.out.print("请输入添加的名字:");
        String admin_name = scanner.nextLine(); //next当接受到空格或者 ' 表示结束
       // System.out.print("请输入管理员的密码:");
        //String admin_pwd = scanner.nextLine();
        //通过Properties
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));

        //获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        // 注册驱动
        Class.forName(driver);
        //得到连接
        Connection connection = DriverManager.getConnection(url,user,password);
        // 组织sql sql语句的 ? 相当于占位符
       // 添加一个记录
        //String sql = "insert into admin values(?,?)";
        //String sql = "update admin set pwd = ? where name = ?";
        String sql = "delete from admin where name = ?";
        //3.2 preparedStatement 对象实现了 preparedStatement 接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3.3 给?赋值
        preparedStatement.setString(1,admin_name);
        //preparedStatement.setString(1,admin_pwd);
        //4.执行DML 语句使用 executeUpdate
        int rows = preparedStatement.executeUpdate();
        System.out.println(rows > 0 ? "执行成功":"执行失败");
        //关闭连接
        preparedStatement.close();
        connection.close();
    }
}

六. JDBC API 总结

  • Driver Manager 驱动管理类  getConnection(url,user,pwd) 获取连接
  • Connection 接口  creatStatement 创建Statement 对象(使用较少,存在注入问题)                 preparedStatement(sql) 生成一个预处理对象
  • Statement 接口   executeUpdate(sql) 执行dml语句 返回影响得到行数                                       executeQuery(sql) 执行查询,返回ResultSet对象                                                                      execute(sql) 执行任意的sql 返回的是布尔值
    • PreparedStatement 接口  excuteUpdate() 执行Dml语句                                                    excuteQuery() 执行查询   返回ResultSet                                                                    excute() 执行任意的sql 返回一个布尔值                                                                              setXxx(站位符索引,占位符的值) 可以解决sql 注入                                                        setObject(站位符的索引,站位符的值)                                                                                  ResultSet(结果集)  next() 方法向下移动一行     同时如果没有下一行,返回false              previous() 向上移动一行                                                                                                      getXX(列的索引 | 列名)         返回对应类的值 接受类型是Xxx                                            getObject(列的索引 | 列名)  返回对应列的值,接受类型为object                                       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bit..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值