Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. package practice2;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.text.NumberFormat;
  9. import java.util.Locale;
  10. import javax.swing.JOptionPane;
  11.  
  12. public class PreparedStatementTest {
  13. public static void main(String[] args) {
  14.  
  15. String url = "jdbc:derby://localhost:1527/EmployeeDB";
  16. String user = "test";
  17. String pass = "tiger";
  18.  
  19. // SQL Injection (隱碼攻擊)
  20. // 輸入 1' OR '1'='1
  21. String inputFirstName = JOptionPane.showInputDialog("請輸入要查詢的員工 first name");
  22.  
  23. String query = "select * from employee where firstname=?"; // 使用問號代表參數,之後設定
  24. System.out.println("query = " + query);
  25.  
  26. // try-with-resource (自動關閉資源)
  27. try (
  28. Connection con = DriverManager.getConnection(url, user, pass);
  29. PreparedStatement pstmt = con.prepareStatement(query); // PreparedStatement
  30. ) {
  31.  
  32. pstmt.setString(1, inputFirstName); // 設定第一個 ? 參數值,因為 firstname欄位是字串型別,所以使用 setString()
  33. ResultSet rs = pstmt.executeQuery(); // 執行查詢
  34. int count = 0; // 記錄找到幾筆資料
  35. while (rs.next()) {
  36. count++;
  37. int id = rs.getInt("id");
  38. String firstName = rs.getString("firstname");
  39. String lastName = rs.getString("lastname");
  40. java.util.Date birthdate = rs.getDate("birthdate");
  41. float salary = rs.getFloat("salary");
  42. // 格式化字串
  43. String s = String.format("%d \t %-20s %s %15s",
  44. id,
  45. firstName + " " + lastName,
  46. birthdate,
  47. NumberFormat.getCurrencyInstance(Locale.US).format(salary));
  48. // 輸出目前所讀到的員工資料
  49. System.out.println(s);
  50. }
  51. if(count == 0) {
  52. System.out.println("查無此人");
  53. }
  54.  
  55. } catch (SQLException ex) {
  56. System.out.println(ex);
  57. } // 無須寫 finally 來 close() 資源
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement