Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. package com.examples.recipes;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11.  
  12. /**
  13. * @author mchapagai The following example shows Java Database Connectivity
  14. */
  15. public class SQLDataAccess {
  16. private static final String MYSQL_CONNECTION = "jdbc:mysql://localhost:3306/data_sampledb";//connection url
  17. private static final String SELECT_EMPLOYEES = "select * from employees";
  18. private static final String EMPLOYEE_ID = "id";
  19. private static final String EMPLOYEE_COUNTRY = "country";
  20. static Logger log = LoggerFactory.getLogger(SQLDataAccess.class);
  21.  
  22. public static void main(String[] args) {
  23. SQLDataAccess dataAccess = new SQLDataAccess();
  24. dataAccess.query();
  25. }
  26.  
  27. private void query() {
  28. /**
  29. * Create the database statement which creates the statement after
  30. * the connection has been made
  31. * To access the Data in the Database using Java Database Connectivity
  32. * We have to process the ResultSet and Execute the query
  33. * Following code Processes resultset and Executes the query
  34. */
  35. ResultSet rs = null;
  36. Statement stmt = null;
  37. Connection conn = createConnection();
  38. try {
  39. stmt = conn.createStatement();
  40. rs = stmt.executeQuery(SELECT_EMPLOYEES);
  41. while (rs.next()) {
  42. String ID = rs.getString(EMPLOYEE_ID);
  43. String Country = rs.getString(EMPLOYEE_COUNTRY);
  44.  
  45. log.info("Employee ID: " + ID);
  46. log.info("Employee Country: " + Country);
  47. }
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. } finally {
  51. try {
  52. rs.close();
  53. stmt.close();
  54. conn.close();
  55. } catch (SQLException ex) {
  56.  
  57. }
  58. }
  59. }
  60.  
  61. /**
  62. * First step to work in the JDBC is to create a connection The
  63. * following line of code creates JDBC connection.
  64. */
  65. private Connection createConnection() {
  66. Connection conn = null;
  67. try {
  68. Class.forName("com.mysql.jdbc.Driver");
  69. conn = DriverManager.getConnection(MYSQL_CONNECTION, "username", "password");
  70. } catch (ClassNotFoundException e) {
  71. e.printStackTrace();
  72. } catch (SQLException e) {
  73. e.printStackTrace();
  74. }
  75. return conn;
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement