Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2017
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.Date;
  7.  
  8. public class JDBCExample {
  9. // jdbc driver name and database url
  10. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  11. static final String JDBC_URL = "jdbc:mysql://localhost/db";
  12.  
  13. // Database credentials
  14. static final String USER = "root";
  15. static final String PASS = "";
  16.  
  17. public static void main(String[] args) {
  18. Connection connection = null;
  19. Statement statement = null;
  20. try {
  21. // register jdbc driver
  22. Class.forName(JDBC_DRIVER);
  23. // open a connection
  24. System.out.println("Connection to database...");
  25. connection = DriverManager.getConnection(JDBC_URL, USER, PASS);
  26.  
  27. // execute a query
  28. System.out.println("Creating a statement...");
  29. statement = connection.createStatement();
  30. String sql = "SELECT * FROM people;";
  31. ResultSet resultSet = statement.executeQuery(sql);
  32.  
  33. // extract data from dataset
  34. while(resultSet.next()) {
  35. int id = resultSet.getInt("id");
  36. String firstName = resultSet.getString("first_name");
  37. String lastName = resultSet.getString("last_name");
  38. Date birth = resultSet.getDate("birth");
  39. Date death = resultSet.getDate("death");
  40. int professionsId = resultSet.getInt("professions_id");
  41.  
  42. System.out.println("id: " + id);
  43. System.out.println("firstName: " + firstName);
  44. System.out.println("lastName: " + lastName);
  45. System.out.println("birth: " + birth);
  46. System.out.println("death: " + death);
  47. System.out.println("professionsId: " + professionsId);
  48.  
  49. }
  50. } catch (SQLException e) {
  51. e.printStackTrace();
  52. } catch (ClassNotFoundException e) {
  53. e.printStackTrace();
  54. } finally {
  55. try {
  56. if(statement != null) {
  57. statement.close();
  58. }
  59. } catch (SQLException e) {
  60. }
  61. try {
  62. if(connection != null) {
  63. connection.close();
  64. }
  65. } catch (Exception e) {
  66. }
  67.  
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement