Advertisement
Guest User

Untitled

a guest
Jan 12th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5. // JDBC driver name and database URL
  6. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  7. static final String DB_URL = "jdbc:mysql://localhost:3306/book";
  8.  
  9. // Database credentials
  10. static final String USER = "root";
  11. static final String PASS = "qwerty";
  12.  
  13. public static void main(String[] args) {
  14. Connection conn = null;
  15. Statement stmt = null;
  16. Scanner scn = new Scanner(System.in);
  17. String book_name = null, author = null, comment = null;
  18.  
  19. try {
  20. // STEP 2: Register JDBC driver
  21. Class.forName("com.mysql.jdbc.Driver");
  22.  
  23. // STEP 3: Open a connection
  24. System.out.print("\nConnecting to database...");
  25. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  26. System.out.println(" SUCCESS!\n");
  27.  
  28. // STEP 4: Ask for user input
  29. System.out.print("Enter book's name: ");
  30. book_name = scn.nextLine();
  31.  
  32. System.out.print("Enter book's author: ");
  33. author = scn.nextLine();
  34.  
  35. System.out.print("Enter your comments: ");
  36. comment = scn.nextLine();
  37.  
  38. // STEP 5: Excute query
  39. System.out.print("\nInserting records into table...");
  40. stmt = conn.createStatement();
  41.  
  42. String sql = "INSERT INTO books (book_name, author, comment)" +
  43. "VALUES (?, ?, ?)";
  44.  
  45. PreparedStatement preparedStatement = conn.prepareStatement(sql);
  46. preparedStatement.setString(1, book_name);
  47. preparedStatement.setString(2, author);
  48. preparedStatement.setString(3, comment);
  49. preparedStatement.executeUpdate();
  50.  
  51. System.out.println(" SUCCESS!\n");
  52.  
  53. } catch(SQLException se) {
  54. se.printStackTrace();
  55. } catch(Exception e) {
  56. e.printStackTrace();
  57. } finally {
  58. try {
  59. if(stmt != null)
  60. conn.close();
  61. } catch(SQLException se) {
  62. }
  63. try {
  64. if(conn != null)
  65. conn.close();
  66. } catch(SQLException se) {
  67. se.printStackTrace();
  68. }
  69. }
  70. System.out.println("Thank you for your patronage!");
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement