Steps to connect Database using JDBC API in Java

  1. Load the JDBC Driver:
  2. Class.forName() ,create's a driver instance and register it with the JDBC driver manager. Syntax: Examples: The above examples creates MySQL and OracleDriverdriver instance and register with JDBC.
  3. Define the connection URL
  4. In JDBC, a connection URL specifies the server host, port, and database name with which to establish a connection.
    Syntax: Example
     
    MySQL : jdbc:mysql://localhost:3306/test
    ORACLE : jdbc:oracle:thin:@localhost:1521:xe
    
    In the above example
    • protocol: jdbc
    • database-host :mysql://localhost
    • port : 3306
    • database-name : test.
  5. Establish the connection to Database
  6. The getConnection() method of DriverManager class is used to establish connection with the database.
    With the connection URL, username,and password, a network connection to the database can be established.
    Once the connection is established, database queries can be performed until the connection is closed.
    Syntax: Example:
  7. Create a Statement object
  8. . Creating a Statement object enables you to send queries and commands to the database.
    The createStatement() method of Connection interface is used to create statement.
    Syntax: Example:
  9. Execute a query or update
  10. . Given a Statement object, The execute(),executeQuery(),executeUpdate(), or executeBatch() method of Statement interface is used to execute queries to the database.
    This method returns the object of ResultSet that can be used to get all the records of a table.
    Syntax: Example: The above example describes, how to create and insert records into student table in database.
  11. Process the results.
  12. When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows and columns that you can process by calls to next and various getXxx methods.
    Syntax: Example: The above code snippet is used to display list of names in Student table.
  13. Close the connection.
  14. When you are finished performing queries and processing results, you should close the connection, releasing resources to the database.
    Syntax: Example
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment