JDBC工具类及增删改查

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/sinat_40662281/article/details/79952476
  • 数据库:
CREATE DATABASE mydb;
#使用数据库
USE mydb;
###创建分类表
CREATE TABLE category(
  cid INT PRIMARY KEY AUTO_INCREMENT  ,
  cname VARCHAR(100)
);
#初始化数据
INSERT INTO category (cname) VALUES('家电');
INSERT INTO category (cname) VALUES('服饰');
INSERT INTO category (cname) VALUES('化妆品');
  • 工具类:注册驱动,获得连接,释放资源
package bull01.JDBCBasis;

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

public class JDBCUtils {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/mydb";
    private static String user = "root";
    private static String password = "root";

    //注册驱动
    static {
        try {
            Class.forName(driver);
        } catch (Exception e) {
            //抛去运行时期异常
            throw new RuntimeException(e);
        }
    }

    //获得连接
    public static Connection getConnections() throws SQLException {
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    //释放资源
    public static void closeResource(Connection conn,Statement st,ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {

            };
        }

        if(st != null) {
            try {
                st.close();
            } catch (SQLException e) {
            }
        }

        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}

  • JDBC增删改查:
package bull02.JDBCUtils;

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

import org.junit.Test;

/*
 * 数据库增删改查
 */
public class CRUDDemo {
    @Test
    public void demo1() {
        //添加
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得语句执行者
            st = conn.createStatement();
            //执行SQL语句
            int r = st.executeUpdate("insert into category (cname) values ('测试')");
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);

        } finally {
            JDBCUtils.closeResource(conn, st, rs);
        }
    }

    @Test
    public void demo2() {
        //删除
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得语句执行者
            st = conn.createStatement();
            //执行SQL语句
            int r = st.executeUpdate("delete from category where cid = 7");
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, st, rs);
        }
    }

    @Test
    public void demo3() {
        //修改
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得语句执行者
            st = conn.createStatement();
            //执行SQL语句
            int r = st.executeUpdate("update category set cname = '食品' where cid = 3");
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, st, rs);
        }
    }

    @Test
    public void demo4() {
        //查询
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得语句执行者
            st = conn.createStatement();
            //执行SQL语句
            rs = st.executeQuery("select * from category");

            while(rs.next()) {
                int cid = rs.getInt("cid");
                String cname = rs.getString("cname");
                System.out.println(cid + "---" + cname);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  • 采用预处理防SQL注入
package bull02.JDBCUtils;
/*
 * 防SQL注入问题
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

public class PrepareDemo {
    @Test
    public void demo1() {
        //添加
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //处理SQL语句
            String sql = "insert into category (cid,cname) values (?,?)";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设置实际参数
            psmt.setInt(1, 4);
            psmt.setString(2, "书本");
            //执行,返回的r是数据库改变的行数
            int r = psmt.executeUpdate();
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, psmt, rs);
        }
    }

    @Test 
    public void demo2() {
        //删除
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获取sql语句
            String sql = "delete from category where cid = ?";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设置实际参数
            psmt.setInt(1, 8);
            //执行
            int r = psmt.executeUpdate();
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, psmt, rs);
        }
    }

    @Test
    public void demo3() {
        //修改
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得SQL语句
            String sql = "update category set cname = ? where cid = ?";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设置实际参数
            psmt.setString(1, "汽车");
            psmt.setInt(2, 4);
            //执行
            int r = psmt.executeUpdate();
            System.out.println(r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            JDBCUtils.closeResource(conn, psmt, rs);
        }

    }

    @Test
    public void demo4() {
        //全部查询
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得SQL语句
            String sql = "select * from category";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设计实际参数,这里没有参数可以设置

            //执行
            rs = psmt.executeQuery();
            while(rs.next()) {
                Integer cid = rs.getInt("cid");
                String cname = rs.getString("cname");
                System.out.println(cid + "---" + cname);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, psmt, rs);
        }
    }

    @Test
    public void demo5() {
        //通过id查询
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获得SQL语句
            String sql = "select * from category where cid = ?";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设置实际参数
            psmt.setInt(1, 1);
            //执行
            rs = psmt.executeQuery();
            if(rs.next()) {
                Integer cid = rs.getInt("cid");
                String cname = rs.getString("cname");
                System.out.println(cid + "---" + cname);
            }
            else {
                System.out.println("查询不到");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, psmt, rs);
        }
    }
}

采用预处理防SQL注入案例

  • 数据库:
USE mydb;
CREATE TABLE USER(
  NAME VARCHAR(50) PRIMARY KEY,
  passwd VARCHAR(50)
);

INSERT INTO USER (NAME,passwd) VALUES ('jack','123456');
  • PreparedDemo:
package bull02.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

public class PreparedDemo {
    @Test
    public void method() {
        String name = "jack #";
        String passwd = "123456";

        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //获得连接
            conn = JDBCUtils.getConnections();
            //获取SQL语句
            String sql = "select * from user where name = ? and passwd = ?";
            //获得预处理对象
            psmt = conn.prepareStatement(sql);
            //设置实际参数
            psmt.setString(1, name);
            psmt.setString(2, passwd);
            //执行
            rs = psmt.executeQuery();

            if(rs.next()) {
                System.out.println("登录成功!");
            }
            else {
                System.out.println("登录失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, psmt, rs);
        }
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页