Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3.  
  4. public class MainSQL {
  5.  
  6.     private Connection connection;
  7.     private Statement statement;
  8.  
  9.     public MainSQL() {
  10.         try {
  11.             Connect();
  12.         } catch (Exception e) {
  13.             System.out.println(e);
  14.         }
  15.  
  16.         System.out.println("Connection established");
  17.  
  18.         try {
  19.             receiveData();
  20.         } catch (SQLException e) {
  21.             System.out.println(e);
  22.         }
  23.  
  24. //        Disconnect();
  25.     }
  26.  
  27.     private void receiveData() throws SQLException {
  28.         String sqlStatement = "select * from listofartists where ArtistID IN (select ArtistID from artists.work);";
  29.         statement = connection.createStatement();
  30.  
  31.         ResultSet rs = statement.executeQuery(sqlStatement);
  32.         int cols = rs.getMetaData().getColumnCount();
  33.  
  34.  
  35.         for (int i = 1; i <= cols; i++) {
  36.             System.out.print(rs.getMetaData().getColumnName(i) + " ");
  37.         }
  38.         System.out.println();
  39.         while(rs.next()){
  40.             for (int i = 1; i <= cols; i++) {
  41.                 String value = rs.getString(i);
  42.                 System.out.print(value + " ");
  43.             }
  44.             System.out.println();
  45.         }
  46.  
  47.         rs.close();
  48.  
  49.         statement.close();
  50.     }
  51.  
  52.     private void Connect() throws Exception {
  53.  
  54.         if(connection != null) return;
  55.  
  56.         try {
  57.             Class.forName("com.mysql.jdbc.Driver");
  58.         } catch (ClassNotFoundException e) {
  59.             throw new Exception("Driver not found");
  60.         }
  61.  
  62.         String url = "jdbc:mysql://localhost:3306/artists?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
  63.         connection = DriverManager.getConnection(url, "root", "chen");
  64.     }
  65.  
  66.     private void Disconnect() {
  67.         if(connection != null){
  68.             try {
  69.                 connection.close();
  70.             } catch (SQLException e) {
  71.                 System.out.println("Could not close connection");
  72.             }
  73.         }
  74.     }
  75.  
  76.  
  77.     public static void main(String[] args) {
  78.         new MainSQL();
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement