java-jdbc-prepareStatment

package com.anlysqx.testJDBC;

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

public class JdbcDemo2 {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testjdbc?useSSL=true&serverTimezone=GMT%2B8", "root", "xxxxxx");
			String id = "1";
			String sql = "select * from user where id = "+id+" or 1=1";
			Statement st = conn.createStatement();
			
			//prepareStatement 之所以能够防止sql注入是因为,预编译后再进行填充,如果还含有逻辑式是无效的,它只填值
			ps = conn.prepareStatement("select * from user where id = ?");
			ps.setString(1, "2 or 1=1");
			rs = ps.executeQuery();
			
//			rs = st.executeQuery(sql);
			
			while(rs.next()){
				System.out.println(rs.getInt(1)+"--"+rs.getString(2)+"--"+rs.getTime(3).toString());
			}
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
}

 

你可能感兴趣的:(java)