Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. package jdbc_test;
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5.  
  6. public class JDBC_Test {
  7. public static void main(String[] args) {
  8.  
  9. String tableName=null;
  10. Scanner input = new Scanner(System.in);
  11. int id=8;
  12.  
  13. System.out.println("Enter the table name: ");
  14. tableName = input.nextLine();
  15.  
  16. try
  17. {
  18.  
  19. Connection con = DriverManager.getConnection(
  20. "jdbc:oracle:thin:@localhost:1521:oracle12c", "system", "oracle12c");
  21.  
  22.  
  23. Statement stmt = con.createStatement();
  24.  
  25.  
  26. ResultSet rs = stmt.executeQuery("select * from "+tableName+"where id='"+id+"'");
  27.  
  28. System.out.printf("%15s%15s","Name","ID");
  29.  
  30. while (rs.next())
  31. {
  32. System.out.printf("n%15s",rs.getString("name"));
  33. }
  34.  
  35. con.close();
  36. stmt.close();
  37. }
  38. catch (Exception e)
  39. {
  40. System.out.println(e);
  41. }
  42. }
  43. }
  44.  
  45. Enter the table name:
  46. t
  47.  
  48. java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
  49.  
  50. try
  51. {
  52. Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle12c", username, password);
  53.  
  54. // You want to prepare a statement so you can pass parameters.
  55. PreparedStatement stmt = con.prepareStatement();
  56.  
  57. // The first question mark (?)
  58. // Assuming this is an INT type. If not, there is setString, setLong, etc.
  59. ps.setInt(1, id);
  60.  
  61. // Note the first question mark is where the ID is supposed to be. This is a parameter.
  62. ResultSet rs = stmt.executeQuery("select * from tableName where id = ?");
  63.  
  64. while (rs.next())
  65. {
  66. // Replace "column_name" with the name of your column
  67. System.out.println(rs.getString("column_name"));
  68. }
  69.  
  70. con.close();
  71. stmt.close();
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement