zoukankan      html  css  js  c++  java
  • PreparedStatement执行sql語句

    import com.loaderman.util.JdbcUtil;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import org.junit.Test;
    /**
     * PreparedStatement執行sql語句
     *
     */
    public class Demo1 {
    
        /**
         * 增加
         */
        @Test
        public void testInsert() {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                //1.获取连接
                conn = JdbcUtil.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 {
                JdbcUtil.close(conn, stmt);
            }
        }
        
        /**
         * 修改
         */
        @Test
        public void testUpdate() {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                //1.获取连接
                conn = JdbcUtil.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 {
                JdbcUtil.close(conn, stmt);
            }
        }
        
        /**
         * 删除
         */
        @Test
        public void testDelete() {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                //1.获取连接
                conn = JdbcUtil.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 {
                JdbcUtil.close(conn, stmt);
            }
        }
        
        /**
         * 查询
         */
        @Test
        public void testQuery() {
            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                //1.获取连接
                conn = JdbcUtil.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 {
                //关闭资源
                JdbcUtil.close(conn,stmt,rs);
            }
        }
    }

    import com.loaderman.util.JdbcUtil;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    /**
     * 模拟用户登录效果
     * @author APPle
     *
     */
    public class Demo2 {
        //模拟用户输入
        //private String name = "ericdfdfdfddfd' OR 1=1 -- ";
        private String name = "eric";
        //private String password = "123456dfdfddfdf";
        private String password = "123456";
    
        /**
         * Statment存在sql被注入的风险
         */
        @Test
        public void testByStatement(){
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
            try {
                //获取连接
                conn = JdbcUtil.getConnection();
                
                //创建Statment
                stmt = conn.createStatement();
                
                //准备sql
                String sql = "SELECT * FROM users WHERE NAME='"+name+"' AND PASSWORD='"+password+"'";
                
                //执行sql
                rs = stmt.executeQuery(sql);
                
                if(rs.next()){
                    //登录成功
                    System.out.println("登录成功");
                }else{
                    System.out.println("登录失败");
                }
                
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(conn, stmt ,rs);
            }
            
        }
        
        /**
         * PreparedStatement可以有效地防止sql被注入
         */
        @Test
        public void testByPreparedStatement(){
            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                //获取连接
                conn = JdbcUtil.getConnection();
                
                String sql = "SELECT * FROM users WHERE NAME=? AND PASSWORD=?";
                
                //预编译
                stmt = conn.prepareStatement(sql);
                
                //设置参数
                stmt.setString(1, name);
                stmt.setString(2, password);
                
                //执行sql
                rs = stmt.executeQuery();
                
                if(rs.next()){
                    //登录成功
                    System.out.println("登录成功");
                }else{
                    System.out.println("登录失败");
                }
                
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(conn, stmt ,rs);
            }
            
        }
    }
    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;
    
    /**
     * jdbc工具类
     * @author APPle
     *
     */
    public class JdbcUtil {
        private static String url = null;
        private static String user = null;
        private static String password = null;
        private static String driverClass = null;
        
        /**
         * 静态代码块中(只加载一次)
         */
        static{
            try {
                //读取db.properties文件
                Properties props = new Properties();
                /**
                 *  . 代表java命令运行的目录
                 *  在java项目下,. java命令的运行目录从项目的根目录开始
                 *  在web项目下,  . java命令的而运行目录从tomcat/bin目录开始
                 *  所以不能使用点.
                 */
                //FileInputStream in = new FileInputStream("./src/db.properties");
                
                /**
                 * 使用类路径的读取方式
                 *  / : 斜杠表示classpath的根目录
                 *     在java项目下,classpath的根目录从bin目录开始
                 *     在web项目下,classpath的根目录从WEB-INF/classes目录开始
                 */
                InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
                
                //加载文件
                props.load(in);
                //读取信息
                url = props.getProperty("url");
                user = props.getProperty("user");
                password = props.getProperty("password");
                driverClass = props.getProperty("driverClass");
                
                
                //注册驱动程序
                Class.forName(driverClass);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("驱程程序注册出错");
            }
        }
    
        /**
         * 抽取获取连接对象的方法
         */
        public static Connection getConnection(){
            try {
                Connection conn = DriverManager.getConnection(url, user, password);
                return conn;
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        
        
        /**
         * 释放资源的方法
         */
        public static void close(Connection conn,Statement stmt){
            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);
                }
            }
        }
        
        public static void close(Connection conn,Statement stmt,ResultSet rs){
            if(rs!=null)
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                    throw new RuntimeException(e1);
                }
            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);
                }
            }
        }
    }

    db.properties

    url=jdbc:mysql://localhost:3306/test
    user=root
    password=root
    driverClass=com.mysql.jdbc.Driver
  • 相关阅读:
    SQL的高级属性-
    查询
    SQL语句
    CSS的创建样式
    表单部分属性值
    HTML的语法和基本标签
    网页制作与HTML基本结构
    小程序button 去边框
    关于axios跨域带cookie
    Uncaught Error: code length overflow. (1604>1056)
  • 原文地址:https://www.cnblogs.com/loaderman/p/10007472.html
Copyright © 2011-2022 走看看