- Import Database Driver:
In Java code, you must first import the database driver package. This is because Java interacts with databases using the JDBC (Java Database Connectivity) API, and each database (e.g., MySQL, Oracle) has its own driver. Complete this step by importing the appropriate driver class; for example, with MySQL, the code is:
javaimport java.sql;
Ensure the corresponding JDBC driver JAR file is added to the project's classpath.
- Load Database Driver:
When the Java program starts, load the database driver using the Class.forName() method. For example:
javaClass.forName("com.mysql.cj.jdbc.Driver");
This step ensures the JVM loads and registers the JDBC driver.
- Establish Connection:
Use the DriverManager.getConnection() method to connect to the database. Provide the database URL, username, and password as parameters; for example:
javaConnection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/database_name", "username", "password");
This step establishes the actual connection to the database.
- Create Statement Object:
After establishing the connection, create a Statement object to execute SQL statements. For example:
javaStatement stmt = conn.createStatement();
The Statement object provides methods to execute SQL queries and retrieve results.
- Execute Query and Process Results:
Use the executeQuery method of the Statement object to run SQL queries and obtain a ResultSet object, which allows accessing query results:
javaResultSet rs = stmt.executeQuery("SELECT * FROM table_name"); while (rs.next()) { String data = rs.getString("column_name"); // Process results }
After processing data, always close the ResultSet, Statement, and Connection objects to release database resources.
This summarizes the five key steps for connecting Java to a database. The process involves critical stages such as loading the driver, establishing the connection, creating the execution object, executing queries, and processing results.