2016年6月16日 星期四

在Eclipse內使用PostgreSQL資料庫

最近工作需要在Eclipse內和PostgreSQL資料庫相連,因此這邊記錄一下使用方式,免得自己以後要用時又得東找西找的。

首先將PostgreSQL的JAR檔匯入到Eclipse內:


接著在Eclipse內撰寫:
  1. import java.sql.*;
  2.  
  3. public class MainProcess {
  4.  
  5.     public static void main(String[] args)
  6.     {
  7.         Connection tempConnection = null;
  8.         Statement tempStatement = null;
  9.         ResultSet tempResultSet = null;
  10.         String tempAction = "";
  11.         String tempSentence = "";
  12.  
  13.         switch( tempAction )
  14.         {
  15.             case "Select":
  16.                 tempSentence = "SELECT * FROM Schemas.Tables WHERE account = 'Kimdick' AND password = '123'";
  17.  
  18.                 break;
  19.             case "Insert":
  20.                 tempSentence = "INSERT INTO Schemas.Tables ( account, password ) VALUES ( 'Kimdick', '123' )";
  21.  
  22.                 break;
  23.             case "Update":
  24.                 tempSentence = "Update Schemas.Tables SET password = '123', email = 'Kimdick@mail' WHERE account = 'Kimdick'";
  25.  
  26.                 break;
  27.             case "Delete":
  28.                 tempSentence = "DELETE FROM Schemas.Tables WHERE account = 'Kimdick'";
  29.  
  30.                 break;
  31.         }
  32.  
  33.         try
  34.         {
  35.             Class.forName( "org.postgresql.Driver" );
  36.             tempConnection = DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/datastream", "postgres", "1234" );
  37.             tempStatement = tempConnection.createStatement();
  38.             tempStatement.executeQuery( tempSentence );
  39.  
  40.             if( tempResultSet != null )
  41.             {
  42.                 tempResultSet.close();
  43.                 tempResultSet = null;
  44.             }
  45.  
  46.             if( tempStatement != null )
  47.             {
  48.                 tempStatement.close();
  49.                 tempStatement = null;
  50.             }
  51.  
  52.             if( tempConnection != null )
  53.             {
  54.                 tempConnection.close();
  55.                 tempConnection = null;
  56.             }
  57.         }
  58.         catch( Exception e )
  59.         {
  60.             e.printStackTrace();
  61.         }
  62.     }
  63. }

  1. DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/datastream", "postgres", "1234" );
這裡是DriverManager.getConnection( "jdbc:postgresql://資料庫IP:Port/Database", 帳號, 密碼 );

沒有留言:

張貼留言