java JDBC (二) 防止注入/参数化

 

package cn.sasa.demo2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JDBCDemo2 {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /**
         * 防止注入攻击 /参数化查询
         * Statement 接口 有个子接口 PreparedStatement --sql预编译
         * 
         */
        String name = "";
        String pwd = "";
        Scanner sc = new Scanner(System.in);
        System.out.println("用户名");
        name = sc.nextLine();
        System.out.println("密码");
        pwd = sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.207:3306/mydb", "root", "XXXXXXXX1");
        
        //String sql = " SELECT * FROM `user` WHERE name='"+ name +"' and pwd='"+ pwd +"' ";
        //Statement state = conn.createStatement();
        //ResultSet rsSet = state.executeQuery(sql);
        
        String sql = " SELECT * FROM `user` WHERE name=? and pwd=? ";
        PreparedStatement pstate = conn.prepareStatement(sql);
        pstate.setObject(1, name);
        pstate.setObject(2, pwd);
        ResultSet rsSet = pstate.executeQuery();
        
        while(rsSet.next()) {
            System.out.println(rsSet.getString("name"));
        }
        
        rsSet.close();
        //state.close();
        pstate.cancel();
        conn.close();
        
    }

}

 

posted @ 2019-01-07 15:13  SasaL  Views(1007)  Comments(0Edit  收藏  举报