Advertisement
rasyid03

manipulasi

May 15th, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 KB | None | 0 0
  1. package javaapplication1;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.sql.ResultSet;
  7. import java.sql.PreparedStatement;
  8.  
  9. public class ManipulasiData {
  10. Connection conn = null;
  11. String url = "jdbc:mysql://localhost/SEWA_RUANG";
  12. String user = "root";
  13. String password = "";
  14. Statement st = null;
  15. ResultSet rs = null;
  16. PreparedStatement pst = null;
  17.  
  18. public static void main(String[] args) {
  19. ManipulasiData app = new ManipulasiData();
  20. app.masukanData();
  21. app.showData();
  22. }
  23.  
  24. public void masukanData() {
  25. System.out.println("**MASUKKAN DATA**");
  26.  
  27. try {
  28. conn = DriverManager.getConnection(url, user, password);
  29. String query = "INSERT INTO ruang(id_ruang , jenis_ruang, harga_sewa) VALUES(?,?,?)";
  30. pst = conn.prepareStatement(query);
  31.  
  32. for (int i = 1; i <= 10; i++) {
  33. pst.setInt(1, i);
  34. pst.setString(2, "ruang-" + i);
  35. pst.setFloat(3, new Float(5.4 * i));
  36. pst.executeUpdate();
  37. }
  38.  
  39. System.out.println("==============================");
  40. System.out.println("**BERHASIL MASUKKAN DATA**");
  41. } catch (SQLException e) {
  42. System.out.println(e.getMessage());
  43. } finally {
  44. System.out.println("==============================");
  45. try {
  46. if (pst != null) { pst.close(); }
  47. if (conn != null) { conn.close(); }
  48. } catch (SQLException e) {
  49. System.out.println(e.getMessage());
  50. }
  51. }
  52. }
  53.  
  54. public void showData() {
  55. System.out.println("**TAMPILKAN DATA**");
  56. System.out.println("==============================");
  57. System.out.println("id_ruang"+"\t"+"jenis_ruang"+"\t"+"\t"+"\t"+"harga_sewa");
  58. try {
  59. conn = DriverManager.getConnection(url, user, password);
  60. pst = conn.prepareStatement("SELECT * FROM ruang");
  61. rs = pst.executeQuery();
  62. while (rs.next()) {
  63. System.out.print(rs.getInt("id_ruang"));
  64. System.out.print("\t"+"\t");
  65. System.out.print(rs.getString("jenis_ruang"));
  66. System.out.print("\t"+"\t");
  67. System.out.println(rs.getFloat("harga_sewa")); }
  68. } catch (SQLException e) {
  69. System.out.println(e.getMessage());
  70. } finally {
  71. System.out.println("==============================");
  72.  
  73. try {
  74. if (rs != null) { rs.close();}
  75. if (pst != null) { pst.close(); }
  76. if (conn != null) { conn.close(); }
  77.  
  78. } catch (SQLException e) {
  79. System.out.println(e.getMessage());
  80. }
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement