Advertisement
Guest User

Untitled

a guest
Nov 11th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. package inf.smart.database;
  2.  
  3. import java.sql.*;
  4.  
  5. public class JDBCExample {
  6.  
  7. private static final String URL = "jdbc:mysql://localhost:3306/mydbtest";
  8. private static final String NAME = "root";
  9. private static final String PASS = "1234";
  10.  
  11. private static Connection con;
  12. private static Statement stmt;
  13. private static ResultSet res;
  14.  
  15. public static void main(String[] args) {
  16.  
  17. try {
  18.  
  19. con = DriverManager.getConnection(URL, NAME, PASS);
  20.  
  21. if (!con.isClosed()) {
  22. System.out.println("Connection is established!");
  23. }
  24.  
  25. stmt = con.createStatement();
  26.  
  27. stmt.executeUpdate("CREATE TABLE Phones (Name CHAR(15), Phone CHAR(15))");
  28. stmt.executeUpdate("INSERT INTO Phones VALUES ('Mike', '0671234567')");
  29. stmt.executeUpdate("INSERT INTO Phones VALUES ('James', '0507654321')");
  30. stmt.executeUpdate("INSERT INTO Phones VALUES ('Merilyn', '0631234567')");
  31. stmt.executeUpdate("INSERT INTO Phones VALUES ('Jonathan', '0687654321')");
  32.  
  33. res = stmt.executeQuery("SELECT * FROM Phones");
  34.  
  35. while (res.next()) {
  36. String name = res.getString(1);
  37. String phone = res.getString("Phone");
  38. System.out.println(name + ": " + phone);
  39. }
  40.  
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. } finally {
  44. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  45. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  46. try { res.close(); } catch(SQLException se) { /*can't do anything */ }
  47. }
  48.  
  49. }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement