Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.util.*;
- public class Main {
- // JDBC driver name and database URL
- static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- static final String DB_URL = "jdbc:mysql://localhost:3306/book";
- // Database credentials
- static final String USER = "root";
- static final String PASS = "qwerty";
- public static void main(String[] args) {
- Connection conn = null;
- Statement stmt = null;
- Scanner scn = new Scanner(System.in);
- String book_name = null, author = null, comment = null;
- try {
- // STEP 2: Register JDBC driver
- Class.forName("com.mysql.jdbc.Driver");
- // STEP 3: Open a connection
- System.out.print("\nConnecting to database...");
- conn = DriverManager.getConnection(DB_URL, USER, PASS);
- System.out.println(" SUCCESS!\n");
- // STEP 4: Ask for user input
- System.out.print("Enter book's name: ");
- book_name = scn.nextLine();
- System.out.print("Enter book's author: ");
- author = scn.nextLine();
- System.out.print("Enter your comments: ");
- comment = scn.nextLine();
- // STEP 5: Excute query
- System.out.print("\nInserting records into table...");
- stmt = conn.createStatement();
- String sql = "INSERT INTO books (book_name, author, comment)" +
- "VALUES (?, ?, ?)";
- PreparedStatement preparedStatement = conn.prepareStatement(sql);
- preparedStatement.setString(1, book_name);
- preparedStatement.setString(2, author);
- preparedStatement.setString(3, comment);
- preparedStatement.executeUpdate();
- System.out.println(" SUCCESS!\n");
- } catch(SQLException se) {
- se.printStackTrace();
- } catch(Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if(stmt != null)
- conn.close();
- } catch(SQLException se) {
- }
- try {
- if(conn != null)
- conn.close();
- } catch(SQLException se) {
- se.printStackTrace();
- }
- }
- System.out.println("Thank you for your patronage!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement