zoukankan      html  css  js  c++  java
  • 二.使用JDBC对数据库CRUD

    一、statement对象介绍  

      Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
      Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
      Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

    1.1、CRUD操作-create

      使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

        Statement statement=connection.createStatement();
        
        String sql1="insert into users(CODE,NAME,STATUS) values('999','蕾蕾','生效')";
        int num=statement.executeUpdate(sql1);
        if(num>0) {
            System.out.println("插入成功");
        }

    1.2、CRUD操作-update

      使用executeUpdate(String sql)方法完成数据修改操作,示例操作:

    Statement statement=connection.createStatement();
        
        String sql2="update users set name='磊磊' where name='蕾蕾'";
        int num1=statement.executeUpdate(sql2);
        if(num1>0) {
            System.out.println("修改成功");
        }

    1.3、CRUD操作-delete

      使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

    String sql3 = "delete from users where id=1"; 
         int num2 = statement.executeUpdate(sql3);
         if(num2>0){
             System.out.println("删除成功!!!");
         }

    1.4、CRUD操作-read

      使用executeQuery(String sql)方法完成数据查询操作,示例操作:

     String sql4 = "select * from users where id=2"; 
        ResultSet rs =statement.executeQuery(sql4);
        while(rs.next()){
            //根据获取列的数据类型,分别调用rs的相应方法映射到java对象中
        }

    二、使用jdbc对数据库增删改查

    2.1、搭建实验环境    

      1、在mysql中创建一个库,并创建user表和插入表的数据。

      SQL脚本如下:

    create database jdbcStudy;
      use jdbcStudy;
      
      create table users(
          id int primary key,
          name varchar(40),
          password varchar(40),
          email varchar(60),
         birthday date
     );

    2、新建一个JavaWeb工程,并导入MySQL数据库驱动。

    3、在src目录下创建一个db.properties文件,如下图所示:

    在db.properties中编写MySQL数据库的连接信息,代码如下所示:

    4、编写一个JdbcUtils工具类,用于连接数据库,获取数据库连接和释放数据库连接,代码如下:

    package me.tanlei.jdbc;
    
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class jdbcUtils {
        private static String driver = null;
        private static String url = null;
        private static String username = null;
        private static String password = null;
    
        static {
            try {
                // 读取db.properties文件中的数据库连接信息
                InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
                Properties properties = new Properties();
                // 从输入字节流读取属性列表(键,值)
                properties.load(in);
                // 获取数据库连接驱动
                driver = properties.getProperty("driver");
                // 获取数据库连接URL地址
                url = properties.getProperty("url");
                // 获取数据库连接用户名
                username = properties.getProperty("username");
                // 获取数据库连接密码
                password = properties.getProperty("password");
    
                // 加载数据库驱动
                Class.forName(driver);
    
            } catch (Exception e) {
                throw new ExceptionInInitializerError(e);
            }
        }
    
        /*
         * 获取数据库连接对象
         */
        public static Connection getConnection() throws SQLException {
            return DriverManager.getConnection(url, username, password);
    
        }
    
        /*
         * 释放资源
         */
        public static void release(Connection connection, Statement statement, ResultSet resultSet) {
            if (resultSet != null) {
                try {
                    // 关闭存储查询结果的ResultSet对象
                    resultSet.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                resultSet = null;
            }
    
            if (statement != null) {
                try {
                    // 关闭负责执行SQL命令的Statement对象
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            if (connection != null) {
                try {
                    // 关闭Connection数据库连接对象
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
        }
    }

    2.2、使用statement对象完成对数据库的CRUD操作

      测试代码如下:

    package me.tanlei.demo;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    import me.tanlei.jdbc.jdbcUtils;
    
    public class jdbcTest {
        @Test
        public void insert() {
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
    
            try {
                // 获取一个数据库连接
                connection = jdbcUtils.getConnection();
                // 通过conn对象获取负责执行SQL命令的Statement对象
                statement = connection.createStatement();
                // 要执行的sql命令
                String sql = "insert into users(id,name,password,email,birthday) values(4,'白虎神皇','123','bhsh@sina.com','1980-09-09')";
                // 执行插入操作,executeUpdate方法返回成功的条数
                int num = statement.executeUpdate(sql);
                if (num > 0) {
                    System.out.println("插入成功");
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                // SQL执行完成之后释放相关资源
                jdbcUtils.release(connection, statement, resultSet);
            }
    
        }
    
        @Test
        public void delete() {
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
            try {
                conn = jdbcUtils.getConnection();
                String sql = "delete from users where id=3";
                st = conn.createStatement();
                int num = st.executeUpdate(sql);
                if (num > 0) {
                    System.out.println("删除成功!!");
                }
            } catch (Exception e) {
                e.printStackTrace();
    
            } finally {
                jdbcUtils.release(conn, st, rs);
            }
        }
    
        @Test
        public void update() {
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
            try {
                conn = jdbcUtils.getConnection();
                String sql = "update users set name='谭磊' where id=4";
                st = conn.createStatement();
                int num = st.executeUpdate(sql);
                if (num > 0) {
                    System.out.println("更新成功!!");
                }
            } catch (Exception e) {
                e.printStackTrace();
    
            } finally {
                jdbcUtils.release(conn, st, rs);
            }
        }
    
        @Test
        public void find() {
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
            try {
                conn = jdbcUtils.getConnection();
                String sql = "select * from users where id=4";
                st = conn.createStatement();
                rs = st.executeQuery(sql);
                if (rs.next()) {
                    System.out.println(rs.getString("name"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                jdbcUtils.release(conn, st, rs);
            }
        }
    }

    三、PreparedStatement对象介绍

      PreperedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避免SQL注入的问题。
      Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率。并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。

    3.1、使用PreparedStatement对象完成对数据库的CRUD操作

      测试代码如下:

    package me.tanlei.demo;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Date;
    
    import org.junit.Test;
    
    import me.tanlei.jdbc.jdbcUtils;
    
    
    
    public class JDBCtestDemo {
       @Test
       public void insert() {
           Connection connection=null;
           PreparedStatement pStatement=null;
           ResultSet resultSet=null;
           
           try {
             //获取一个数据库连接
            connection=jdbcUtils.getConnection();
            //要执行的SQL命令,SQL中的参数使用?作为占位符
            String sql="insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";
            //通过conn对象获取负责执行SQL命令的prepareStatement对象
            pStatement=connection.prepareStatement(sql);
            pStatement.setInt(1, 1);//id是int类型的
            pStatement.setString(2, "tanlei");//name是varchar(字符串类型)
            pStatement.setString(3, "123");//password是varchar(字符串类型)
            pStatement.setString(4, "bhsh@sina.com");//email是varchar(字符串类型)
            pStatement.setDate(5, new java.sql.Date(new Date().getTime()));//birthday是date类型
             //执行插入操作,executeUpdate方法返回成功的条数
            int num=pStatement.executeUpdate();
            if(num>0) {
                System.out.println("更新成功");
            }
           } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            jdbcUtils.release(connection, pStatement, resultSet);
        }
           
       }
       @Test
       public void update() {
          Connection connection=null;
          PreparedStatement pStatement=null;
          ResultSet resultSet=null;
          
          try {
            connection=jdbcUtils.getConnection();
            String sql="update users set name=?,email=? where id=?";
            pStatement=connection.prepareStatement(sql);
            pStatement.setString(1, "谭磊");
            pStatement.setString(2, "27300@qq.com");
            pStatement.setInt(3, 1);
            int num=pStatement.executeUpdate();
            if(num>0) {
                System.out.println("更新成功");
            }
          } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            jdbcUtils.release(connection, pStatement, resultSet);
        }
          
       }
    }
  • 相关阅读:
    Linux安装Nginx
    CentOS7上安装google谷歌浏览器
    解决MYSQL的错误:Got a packet bigger than 'max_allowed_packet' bytes
    Mysql ERROR 1067: Invalid default value for 字段
    Mysql查看版本号的五种方式介绍
    linux下mysql 查看默认端口号与修改端口号方法
    yum 和 rpm安装mysql彻底删除
    SpringBootSecurity学习(06)网页版登录方法级别的权限
    SpringBootSecurity学习(05)网页版登录内存中配置默认用户
    SpringBootSecurity学习(04)网页版登录其它授权和登录处理
  • 原文地址:https://www.cnblogs.com/tanlei-sxs/p/9493005.html
Copyright © 2011-2022 走看看