Nearby lessons

9 of 37

JDBC - First Complete Program

📌 What You Will Learn
  • The six standard steps of every JDBC program
  • The JDBC URL and how to read it
  • Loading and registering the driver (old vs modern)
  • Your first complete JDBC program (modern MySQL)
  • Common beginner errors and their fixes

First Complete Program is a fundamental part of database programming with JDBC. This lesson explains Your First Complete JDBC Program (Modern) and Common Beginner Errors and Fixes with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Your First Complete JDBC Program (Modern)

Here is the full six-step program for MySQL (Type-4 driver). This is the modern replacement for the old JDBC-ODBC examples in the classic material:

To run it, put the MySQL connector JAR in the classpath:

Example01
JCode Cell
1import java.sql.*;
2 
3public class JdbcDemo {
4 public static void main(String[] args) throws Exception {
5 // 1. Load & register driver (optional in JDBC 4.0+)
6 // Class.forName("com.mysql.cj.jdbc.Driver");
7 
8 // 2. Establish connection
9 Connection con = DriverManager.getConnection(
10 "jdbc:mysql://localhost:3306/company", "root", "password");
11 
12 // 3. Create statement
13 Statement st = con.createStatement();
14 
15 // 4. Send & execute query
16 ResultSet rs = st.executeQuery("SELECT * FROM employee");
17 
18 // 5. Process results
19 while (rs.next()) {
20 System.out.println(rs.getInt(1) + ".." + rs.getString(2)
21 + ".." + rs.getDouble(3));
22 }
23 
24 // 6. Close connection
25 con.close();
26 }
27}

Your First Complete JDBC Program (Modern)

Example02
JCode Cell
1java -cp .;mysql-connector-j.jar JdbcDemo (Windows - ';' separator)
2java -cp .:mysql-connector-j.jar JdbcDemo (Linux/Mac - ':' separator)

Common Beginner Errors and Fixes

ErrorWhy it happensFix
ClassNotFoundExceptionDriver JAR not in classpath / wrong driver class nameAdd the JAR; check the exact driver class name
SQLException: No suitable driverWrong JDBC URL, or driver not loadedCheck the URL prefix (jdbc:mysql:...)
Access denied for userWrong username or passwordCheck credentials
Unknown databaseThe database name in the URL does not existCreate the database first
Connection refusedMySQL server is not runningStart the MySQL server
📝 Key Takeaways
  • Six steps: load driver → connect → statement → execute → process → close.
  • JDBC URL = jdbc : subprotocol : subname (always starts with jdbc).
  • Class.forName() was needed before JDBC 4.0; now drivers auto-load.
  • executeQuery() is for SELECT; it returns a ResultSet.
  • Use rs.next() to walk through rows and getXXX() to read values.
  • Always close resources; try-with-resources does it automatically.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4