Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7.  
  8. public class MySQLAccess {
  9.  
  10. private Connection connect = null;
  11. private Statement statement = null;
  12. private ResultSet resultSet = null;
  13.  
  14. public void readDataBase() throws Exception {
  15. try {
  16. // This will load the MySQL driver, each DB has its own driver
  17. Class.forName("com.mysql.jdbc.Driver");
  18. // Setup the connection with the DB
  19. connect = DriverManager
  20. .getConnection("jdbc:mysql://localhost/merx?"
  21. + "user=root&password=admin");
  22.  
  23. // Statements allow to issue SQL queries to the database
  24. statement = connect.createStatement();
  25. // Result set get the result of the SQL query
  26. resultSet = statement
  27. .executeQuery("select * from merx.inventory;");
  28. writeResultSet(resultSet);
  29.  
  30. } catch (Exception e) {
  31. throw e;
  32. } finally {
  33. close();
  34. }
  35. }
  36.  
  37. private void writeResultSet(ResultSet resultSet) throws SQLException {
  38. ResultSetMetaData resMeta = resultSet.getMetaData();
  39. int colCount = resMeta.getColumnCount();
  40.  
  41. while (resultSet.next()) {
  42. for (int i = 1; i <= colCount - 1; i++) {
  43. System.out.print(resultSet.getObject(i).toString() + "|");
  44. }
  45. System.out.println(resultSet.getObject(colCount).toString());
  46. }
  47. }
  48.  
  49. // You need to close the resultSet
  50. private void close() {
  51.  
  52. try {
  53. if (resultSet != null) {
  54. resultSet.close();
  55. }
  56.  
  57. if (statement != null) {
  58. statement.close();
  59. }
  60.  
  61. if (connect != null) {
  62. connect.close();
  63. }
  64. } catch (Exception e) {
  65.  
  66. }
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement