JDBC(Java Database Connectivity) is a channel between your Java program and databases i.e it establishes a link between the two to send data.
Steps for JDBC Connection:
1. Load the Driver: Here we load the driver’s class before using it in the program .
For oracle database:
Class.forName("oracle.jfbc.driver.OracleDriver");
For MySql database:
Class.forName("com.mysql.jdbc.Driver");
2. Create Connections: After loading the driver, establish connections using :
For oracle database:
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,username,password);
For MySql database:
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,username,password);
where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, 3306 is the port number and test is the database name which I have created. You can change the database name.
Username: The default username for the mysql database is root.
Password: It is the password given by the user at the time of installing the mysql database. In this example, we are going to use root as the password.
3. Create a statement: Creates a statement by using createStatement() method.
Statement st = con.createStatement();
4. Execute the query: Execute queries to the database by using executeQuery() method .
ResultSet rs=st.executeQuery(query);
5. Close the connection object : The close() method is used to close the connection.
con.close();
Example: Create a constructor in DAO user.java to create connections. Here I am using MySql database.
private Connection con;
public user() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
} catch (Exception e) {
e.printStackTrace();
}
}
Creating statements and executing queries will be written in their respective methods.