SQL 注入

 

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

public class JdbcTransaction {

 public static void main(String[] args) throws SQLException{
  
  String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
  String user="root";
  String pass="password";
  String sql="select * from tx where id='%' or 1 =1";
  Connection conn=getConnection(url, user, pass);
  
//  Statement st=conn.createStatement();
//  PreparedStatement st=conn.prepareStatement(sql);
  //SQL 加? 设置参数防注入
  sql="select * from tx where id=?";
  PreparedStatement st=conn.prepareStatement(sql);
  st.setInt(1, 3);
  ResultSet rs=st.executeQuery();
  while(rs.next()){
   int id=rs.getInt(1);
   int num=rs.getInt("num");
   System.out.println("id="+id+ " num="+num);
  }
  
  rs.close();
  st.close();
  conn.close();
 }
 
 public static Connection getConnection(String url,String user,String password)throws SQLException{
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
  Connection conn=DriverManager.getConnection(url, user, password);
  return conn;
 }

}

你可能感兴趣的:(jdbc)