How to Connect to Database in Java: Simple Guide with Example
To connect to a database in Java, use the
JDBC API by loading the database driver, creating a Connection with DriverManager.getConnection(), and then using Statement or PreparedStatement to execute SQL queries. Always close the connection after use to free resources.Syntax
Here is the basic syntax to connect to a database using JDBC in Java:
- Load the driver: This tells Java which database type you want to use.
- Get a connection: Use
DriverManager.getConnection()with the database URL, username, and password. - Create a statement: To run SQL commands.
- Execute queries: Run SQL and get results.
- Close connection: Always close to avoid resource leaks.
java
Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "user", "password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM tablename"); // process results rs.close(); stmt.close(); conn.close();
Example
This example connects to a MySQL database, runs a simple query, and prints the results.
java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DatabaseConnectExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/testdb"; String user = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name FROM users"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("User ID: " + id + ", Name: " + name); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output
User ID: 1, Name: Alice
User ID: 2, Name: Bob
Common Pitfalls
- Missing driver: Forgetting to add the JDBC driver library to your project causes
ClassNotFoundException. - Wrong URL format: The JDBC URL must match your database type and host.
- Not closing connections: Leads to resource leaks and can crash your app.
- Ignoring exceptions: Always catch and handle SQL exceptions to debug issues.
java
/* Wrong way: Missing driver load */ Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass"); /* Right way: Load driver first */ Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Quick Reference
Remember these key points when connecting to a database in Java:
- Use the correct JDBC driver for your database.
- Format the JDBC URL properly (e.g.,
jdbc:mysql://host:port/dbname). - Always close
ResultSet,Statement, andConnectionobjects. - Handle exceptions to catch connection or query errors.
Key Takeaways
Load the correct JDBC driver before connecting to the database.
Use DriverManager.getConnection() with the right URL, username, and password.
Always close your database resources to prevent leaks.
Handle exceptions to identify and fix connection issues.
Check your JDBC URL format matches your database type and host.