jdbc
jdbc
2. JDBC Setup
Add JDBC Driver Dependency
For MySQL, include the JDBC driver in your project:
xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
Manually Download JDBC Driver Download the MySQL JDBC driver here.
String sql = "CREATE TABLE employees (id INT PRIMARY KEY, name
VARCHAR(50), salary DOUBLE)";
stmt.executeUpdate(sql);
System.out.println("Table created successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
b) Inserting Data
java
import java.sql.Connection;
import java.sql.Statement;
String sql = "INSERT INTO employees VALUES (1, 'John Doe', 50000)";
stmt.executeUpdate(sql);
System.out.println("Data inserted successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Retrieving Data with ResultSet
java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
Next Steps
Since you're invested in Java and Spring Boot, learning Spring Data JPA would be a
great next step—it simplifies database interactions significantly! Let me know if
you'd like a guide on that 🚀.
What are best practices for using JDBC?How does JDBC compare to Hibernate?