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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM