Guest User

Untitled

a guest
Mar 16th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import java.io.PrintStream;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7.  
  8. /**
  9. * Connect to an Oracle database and perform queries/updates. Easily adaptable
  10. * to other databases.
  11. * <p>
  12. * It will print the query column names/results dynamically, just like with the
  13. * PSQL client or SQLPLUS.
  14. * <p>
  15. * TODO: decide column width to print based on column value. Currently it's just
  16. * using two tabs.
  17. * <p>
  18. * Example of execution:
  19. * java -cp .:ojdbc5.jar OracleJdbcClient 127.0.0.1 1521 xe user pwd "SELECT 1 from dual"
  20. *
  21. * @since Mar 7, 2018
  22. * @author Ulisses Lima
  23. */
  24. public class OracleJdbcClient {
  25. public static void main(String[] argv) throws SQLException {
  26. PrintStream out = System.out;
  27. out.println("-------- Oracle JDBC Connection Testing ------");
  28.  
  29. try {
  30. Class.forName("oracle.jdbc.driver.OracleDriver");
  31. } catch (ClassNotFoundException e) {
  32. out.println("Where is your Oracle JDBC Driver? Pass the jar with -cp");
  33. e.printStackTrace();
  34. return;
  35. }
  36.  
  37. out.println("Oracle JDBC Driver Registered!");
  38.  
  39. Connection connection = null;
  40. try {
  41. out.println("host " + argv[0]);
  42. out.println("port " + argv[1]);
  43. out.println("sid " + argv[2]);
  44. out.println("user " + argv[3]);
  45. out.println("pass " + argv[4]);
  46.  
  47. connection = DriverManager.getConnection("jdbc:oracle:thin:@" + argv[0] + ":" + argv[1] + ":" + argv[2],
  48. argv[3], argv[4]);
  49. } catch (SQLException e) {
  50. out.println("Connection Failed! Check output console");
  51. e.printStackTrace();
  52. return;
  53. }
  54.  
  55. if (connection != null) {
  56. out.println("connection ok");
  57. String sql = argv[5];
  58.  
  59. Statement stmt = connection.createStatement();
  60. out.println("command: " + sql);
  61. ResultSet rs = null;
  62. if (sql.toLowerCase().startsWith("select")) {
  63. rs = stmt.executeQuery(sql);
  64.  
  65. int cols = rs.getMetaData().getColumnCount();
  66. for (int i = 1; i < cols + 1; i++) {
  67. out.print(rs.getMetaData().getColumnName(i) + "\t\t");
  68. }
  69. out.println();
  70.  
  71. while (rs.next()) {
  72. for (int i = 1; i < cols + 1; i++) {
  73. out.print(rs.getObject(i) + "\t\t");
  74. }
  75. out.println();
  76. }
  77. } else {
  78. int n = stmt.executeUpdate(sql);
  79. out.println("rows affected: " + n);
  80. }
  81. } else {
  82. out.println("Failed to make connection!");
  83. }
  84. }
  85. }
Add Comment
Please, Sign In to add comment