JAVAEE学习之JDBC

JDBC接口核心的API:

            java.sql.*   和  javax.sql.*

        |- Driver接口: 表示java驱动程序接口。所有的具体的数据库厂商要来实现此接口。
            |- connect(url, properties):  连接数据库的方法。
                    url: 连接数据库的URL 
                        URL语法: jdbc协议:数据库子协议://主机:端口/数据库
                        user: 数据库的用户名
                        password: 数据库用户密码
        |- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序
            |-registerDriver(driver)  : 注册驱动类对象
            |-Connection getConnection(url,user,password);  获取连接对象

        |- Connection接口: 表示java程序和数据库的连接对象。
                |- Statement createStatement() : 创建Statement对象
                |- PreparedStatement prepareStatement(String sql)  创建PreparedStatement对象
                |- CallableStatement prepareCall(String sql) 创建CallableStatement对象

        |- Statement接口: 用于执行静态的sql语句
                |- int executeUpdate(String sql)  : 执行静态的更新sql语句(DDL,DML)
                |- ResultSet executeQuery(String sql)  :执行的静态的查询sql语句(DQL)

            |-PreparedStatement接口:用于执行预编译sql语句
                    |- int executeUpdate() : 执行预编译的更新sql语句(DDL,DML)
                    |-ResultSet executeQuery()  : 执行预编译的查询sql语句(DQL)

                |-CallableStatement接口:用于执行存储过程的sql语句(call xxx)
                        |-ResultSet executeQuery()  : 调用存储过程的方法


        |- ResultSet接口:用于封装查询出来的数据
                |- boolean next() : 将光标移动到下一行
                |-getXX() : 获取列的值

JDBCUtils.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCUtils {

    public static Connection getConnection(){

        //  String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

        //  String driverName = "oracle.jdbc.driver.OracleDriver";

        String driverName = "com.mysql.jdbc.Driver";


        //  String url = "jdbc:sqlserver://localhost:1433; DataBaseName = studentManager";

        //  String url = "jdbc:oracle:thin:@localhost:1521:test";

        String url = "jdbc:mysql://localhost:3306/test";

        String username = "root";

        String password = "root";

        Connection conn = null;

        try{

            Class.forName(driverName);

            conn = DriverManager.getConnection(url,username,password);

            System.out.println("success");

        }catch (Exception e) {

            e.printStackTrace();

        }
        return conn;

    }

    public static void close(ResultSet rs, Statement sta , Connection con)  
    {  
        try {  
            if(null != rs)  
            {  
                rs.close();  
                rs = null ;  
            }  

            if(null != sta)  
            {  
                sta.close();  
                sta = null ;  
            }  

            if(null != con)  
            {  
                con.close();  
                con = null ;  
            }  

        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  


  /**
     * 执行DDL语句(创建表)
     */
    @Test
    public void test1(){
        Statement stmt = null;
        Connection conn = null;
        try {
            //1.驱动注册程序
            //Class.forName("com.mysql.jdbc.Driver");

            //2.获取连接对象
            //conn = DriverManager.getConnection(url, user, password);
            Connection conn = JDBCutils.getConnection();

            //3.创建Statement
            stmt = conn.createStatement();

            //4.准备sql
            String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";

            //5.发送sql语句,执行sql语句,得到返回结果
            int count = stmt.executeUpdate(sql);

            //6.输出
            System.out.println("影响了"+count+"行!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //7.关闭连接(顺序:后打开的先关闭)
            if(stmt!=null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            if(conn!=null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
        }
    }

使用Statement执行sql语句:

    /**
     * 增加
     */
    @Test
    public void testInsert(){
        Connection conn = null;
        Statement stmt = null;
        try {
            //通过工具类获取连接对象
            conn = JDBCUtils.getConnection();

            //3.创建Statement对象
            stmt = conn.createStatement();

            //4.sql语句
            String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";

            //5.执行sql
            int count = stmt.executeUpdate(sql);

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //关闭资源
            /*if(stmt!=null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            if(conn!=null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }*/
            JDBCUtils.close(res, stmt,conn);
        }
    }

/**
     * 修改
     */
    @Test
    public void testUpdate(){
        Connection conn = null;
        Statement stmt = null;
        //模拟用户输入
        String name = "陈六";
        int id = 3;
        try {
            /*//1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2.获取连接对象
            conn = DriverManager.getConnection(url, user, password);*/
            //通过工具类获取连接对象
            conn = JDBCUtils.getConnection();

            //3.创建Statement对象
            stmt = conn.createStatement();

            //4.sql语句
            String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";

            System.out.println(sql);

            //5.执行sql
            int count = stmt.executeUpdate(sql);

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //关闭资源
            /*if(stmt!=null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            if(conn!=null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }*/
            JDBCUtils.close(res, stmt,conn);
        }
}

/**
     * 删除
     */
    @Test
    public void testDelete(){
        Connection conn = null;
        Statement stmt = null;
        //模拟用户输入
        int id = 3;
        try {
            /*//1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2.获取连接对象
            conn = DriverManager.getConnection(url, user, password);*/
            //通过工具类获取连接对象
            conn = JDBCUtils.getConnection();

            //3.创建Statement对象
            stmt = conn.createStatement();

            //4.sql语句
            String sql = "DELETE FROM student WHERE id="+id+"";

            //5.执行sql
            int count = stmt.executeUpdate(sql);

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally{
            //关闭资源
            /*if(stmt!=null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            if(conn!=null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }*/
            JDBCUtils.close(res, stmt,conn);
        }
    }
}

/**
 * 使用Statement执行DQL语句(查询操作)
 */
public class Demo3 {

    @Test
    public void test1(){
        Connection conn = null;
        Statement stmt = null;
        try{
            //获取连接
            conn = JDBCUtils.getConnection();
            //创建Statement
            stmt = conn.createStatement();
            //准备sql
            String sql = "SELECT * FROM student";
            //执行sql
            ResultSet rs = stmt.executeQuery(sql);

            //移动光标
            /*boolean flag = rs.next();

            flag = rs.next();
            flag = rs.next();
            if(flag){
                //取出列值
                //索引
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String gender = rs.getString(3);
                System.out.println(id+","+name+","+gender);

                //列名称
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }*/

            //遍历结果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }

        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            JDBCUtils.close(res, stmt,conn);
        }
    }
}

使用PreparedStatement执行sql语句:(预编译检查语法后设置参数)

/**
     * 增加
     */
    @Test
    public void testInsert() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();

            //2.准备预编译的sql
            String sql = "INSERT INTO student(NAME,gender) VALUES(?,?)"; //?表示一个参数的占位符

            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);

            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setString(1, "李四");
            stmt.setString(2, "男");

            //5.发送参数,执行sql
            int count = stmt.executeUpdate();

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(res, stmt,conn);
        }
    }


/**
     * 修改
     */
    @Test
    public void testUpdate() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();

            //2.准备预编译的sql
            String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符

            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);

            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setString(1, "王五");
            stmt.setInt(2, 9);

            //5.发送参数,执行sql
            int count = stmt.executeUpdate();

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(res, stmt,conn);
        }
    }

/**
     * 删除
     */
    @Test
    public void testDelete() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();

            //2.准备预编译的sql
            String sql = "DELETE FROM student WHERE id=?"; //?表示一个参数的占位符

            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);

            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setInt(1, 9);

            //5.发送参数,执行sql
            int count = stmt.executeUpdate();

            System.out.println("影响了"+count+"行");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(res, stmt,conn);
        }
    }

/**
     * 查询
     */
    @Test
    public void testQuery() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();

            //2.准备预编译的sql
            String sql = "SELECT * FROM student"; 

            //3.预编译
            stmt = conn.prepareStatement(sql);

            //4.执行sql
            rs = stmt.executeQuery();

            //5.遍历rs
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtils.close(res, stmt,conn);
        }
    }
}

PreparedStatement vs Statment

1)语法不同:PreparedStatement可以使用预编译的sql,而Statment只能使用静态的sql

2)效率不同: PreparedStatement可以使用sql缓存区,效率比Statment高

3)安全性不同: PreparedStatement可以有效防止sql注入,而Statment不能防止sql注入。


CallableStatement执行存储过程:

/**
 * 使用CablleStatement调用存储过程
 *
 */
public class Demo1 {

    /**
     * 调用带有输入参数的存储过程
     * CALL pro_findById(4);
     */
    @Test
    public void test1(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JdbcUtil.getConnection();

            //准备sql
            String sql = "CALL pro_findById(?)"; //可以执行预编译的sql

            //预编译
            stmt = conn.prepareCall(sql);

            //设置输入参数
            stmt.setInt(1, 6);

            //发送参数
            rs = stmt.executeQuery(); //注意: 所有调用存储过程的sql语句都是使用executeQuery方法执行!!!

            //遍历结果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }

    /**
     * 执行带有输出参数的存储过程
     * CALL pro_findById2(5,@NAME);
     */
    @Test
    public void test2(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JdbcUtil.getConnection();
            //准备sql
            String sql = "CALL pro_findById2(?,?)"; //第一个?是输入参数,第二个?是输出参数

            //预编译
            stmt = conn.prepareCall(sql);

            //设置输入参数
            stmt.setInt(1, 6);
            //设置输出参数(注册输出参数)
            /**
             * 参数一: 参数位置
             * 参数二: 存储过程中的输出参数的jdbc类型    VARCHAR(20)
             */
            stmt.registerOutParameter(2, java.sql.Types.VARCHAR);

            //发送参数,执行
            stmt.executeQuery(); //结果不是返回到结果集中,而是返回到输出参数中

            //得到输出参数的值
            /**
             * 索引值: 预编译sql中的输出参数的位置
             */
            String result = stmt.getString(2); //getXX方法专门用于获取存储过程中的输出参数

            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值