Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1.  
  2. package practice2;
  3.  
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.text.NumberFormat;
  10. import java.util.Locale;
  11. import javax.swing.JOptionPane;
  12.  
  13. public class SQLInjectionTest {
  14.  
  15. public static void main(String[] args) {
  16. String url = "jdbc:derby://localhost:1527/EmployeeDB";
  17. String user = "test";
  18. String pass = "tiger";
  19. // SQL Injection (隱碼攻擊)
  20. // 輸入 1' OR '1'='1
  21. String inputFirstName = JOptionPane.showInputDialog("請輸入要查詢的員工 first name");
  22. // select * from employee where firstname='xxx'
  23. String query = "select * from employee where firstname='" + inputFirstName + "'";
  24. System.out.println("query = " + query);
  25. // try-with-resource (自動關閉資源)
  26. try (
  27. Connection con = DriverManager.getConnection(url, user, pass);
  28. Statement stmt = con.createStatement();
  29. ResultSet rs = stmt.executeQuery(query);
  30. ) {
  31. int count = 0; // 記錄找到幾筆資料
  32. while (rs.next()) {
  33. count++;
  34. int id = rs.getInt("id");
  35. String firstName = rs.getString("firstname");
  36. String lastName = rs.getString("lastname");
  37. java.util.Date birthdate = rs.getDate("birthdate");
  38. float salary = rs.getFloat("salary");
  39.  
  40. // 格式化字串 String.format( 字串格式指定 , 值1 , 值2 , ... )
  41. // %d 整數格式
  42. // %s 字串格式
  43. // %f 浮點數格式
  44. // %-20s 總寬度20個字並靠左對齊
  45. // %15s 總寬度15個字
  46.  
  47. // 貨幣格式化 NumberFormat.getCurrencyInstance( 國家地區 ).format( 值 )
  48. // 指定國家地區 Locale
  49.  
  50. String s = String.format("%d \t %-20s %s %15s",
  51. id,
  52. firstName + " " + lastName,
  53. birthdate,
  54. NumberFormat.getCurrencyInstance(Locale.US).format(salary));
  55. // 輸出目前所讀到的員工資料
  56. System.out.println(s);
  57. }
  58.  
  59. if(count == 0) {
  60. System.out.println("查無此人");
  61. }
  62.  
  63. } catch (SQLException ex) {
  64. System.out.println(ex);
  65. } // 無須寫 finally 來 close() 資源
  66.  
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement