Connect to the database.
Class.forName("oracle.jdbc.driver.OracleDriver");
//register code for MySQL database
Class.forName("com.mysql.jdbc.Driver");
Note: Since JDBC 4.0, no need to registering the driver.
public static Connection getConnection(String url,String name,String password)
throws SQLException
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//oracle connection
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
- We can use JDBC API to handle database using Java program and can perform the following activities:
- 1. Register the Driver class
- The forName() method of Class is used to register the Driver class.
- This method is used to dynamically load the Driver class.
- Syntax:
- Example:
Class.forName("oracle.jdbc.driver.OracleDriver");
//register code for MySQL database
Class.forName("com.mysql.jdbc.Driver");
Note: Since JDBC 4.0, no need to registering the driver.
- 2. Create connection
- The getConnection() method of DriverManager class is used to establish a connection with the database.
- Syntax:
public static Connection getConnection(String url,String name,String password)
throws SQLException
- Example:
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//oracle connection
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
- 3. Create statement
- The createStatement() method of Connection interface is used to create a statement. The object of the statement is responsible to execute queries with the database.
- Syntax:
- Example:
- 4. Execute queries
- The executeQuery() 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:
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
- 5. Close connection
- By closing the connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
- Syntax:
- Example:
Tags:
Java