Skip to content

Commit 502d907

Browse files
committed
jdbd-and-databases
1 parent ccd7fec commit 502d907

File tree

3 files changed

+248
-0
lines changed

3 files changed

+248
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
To connect to a database using JDBC, you need to follow these steps:
2+
3+
1. **Load the JDBC Driver**: Load the appropriate JDBC driver for the database you want to connect to. The driver class must be included in your classpath.
4+
5+
2. **Establish Connection**: Create a connection to the database by providing the database URL, username, and password.
6+
7+
3. **Create Statement**: Create a Statement object to execute SQL queries against the database.
8+
9+
4. **Execute Query**: Execute SQL queries using the Statement object.
10+
11+
5. **Process Results**: Process the results returned by the query.
12+
13+
6. **Close Resources**: Close the ResultSet, Statement, and Connection objects when you're done to release database resources.
14+
15+
Here's an example of how to connect to a MySQL database using JDBC:
16+
17+
```java
18+
import java.sql.*;
19+
20+
public class MySQLExample {
21+
public static void main(String[] args) {
22+
// Database connection parameters
23+
String url = "jdbc:mysql://localhost:3306/mydatabase";
24+
String username = "username";
25+
String password = "password";
26+
27+
// JDBC objects
28+
Connection connection = null;
29+
Statement statement = null;
30+
ResultSet resultSet = null;
31+
32+
try {
33+
// Load the MySQL JDBC driver
34+
Class.forName("com.mysql.cj.jdbc.Driver");
35+
36+
// Establish connection
37+
connection = DriverManager.getConnection(url, username, password);
38+
39+
// Create statement
40+
statement = connection.createStatement();
41+
42+
// Execute query
43+
resultSet = statement.executeQuery("SELECT * FROM mytable");
44+
45+
// Process results
46+
while (resultSet.next()) {
47+
int id = resultSet.getInt("id");
48+
String name = resultSet.getString("name");
49+
// Process other columns as needed
50+
System.out.println("ID: " + id + ", Name: " + name);
51+
}
52+
} catch (ClassNotFoundException e) {
53+
e.printStackTrace();
54+
} catch (SQLException e) {
55+
e.printStackTrace();
56+
} finally {
57+
// Close resources
58+
try {
59+
if (resultSet != null) resultSet.close();
60+
if (statement != null) statement.close();
61+
if (connection != null) connection.close();
62+
} catch (SQLException e) {
63+
e.printStackTrace();
64+
}
65+
}
66+
}
67+
}
68+
```
69+
70+
Replace `"jdbc:mysql://localhost:3306/mydatabase"`, `"username"`, and `"password"` with your actual database URL, username, and password respectively.
71+
72+
Remember to handle exceptions properly and close resources in a finally block to ensure proper cleanup even if an exception occurs.
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
To execute SQL statements and transactions using JDBC, you can use the Statement and PreparedStatement interfaces. Here's how you can execute SQL statements and transactions:
2+
3+
### Executing SQL Statements
4+
5+
1. **Statement**: Use when you have a static SQL query that does not contain user input.
6+
7+
```java
8+
try {
9+
Statement statement = connection.createStatement();
10+
ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");
11+
// Process ResultSet
12+
statement.close();
13+
} catch (SQLException e) {
14+
e.printStackTrace();
15+
}
16+
```
17+
18+
2. **PreparedStatement**: Use when you have a dynamic SQL query that may contain user input.
19+
20+
```java
21+
try {
22+
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM my_table WHERE id = ?");
23+
preparedStatement.setInt(1, 1); // Set parameter values
24+
ResultSet resultSet = preparedStatement.executeQuery();
25+
// Process ResultSet
26+
preparedStatement.close();
27+
} catch (SQLException e) {
28+
e.printStackTrace();
29+
}
30+
```
31+
32+
### Executing Transactions
33+
34+
1. **Auto-commit Mode**: By default, JDBC operates in auto-commit mode, where each SQL statement is automatically committed as soon as it is executed. To start a transaction, you need to disable auto-commit.
35+
36+
```java
37+
try {
38+
connection.setAutoCommit(false); // Disable auto-commit
39+
// Execute SQL statements
40+
connection.commit(); // Commit transaction
41+
} catch (SQLException e) {
42+
e.printStackTrace();
43+
try {
44+
connection.rollback(); // Rollback transaction if an exception occurs
45+
} catch (SQLException ex) {
46+
ex.printStackTrace();
47+
}
48+
} finally {
49+
try {
50+
connection.setAutoCommit(true); // Enable auto-commit
51+
} catch (SQLException ex) {
52+
ex.printStackTrace();
53+
}
54+
}
55+
```
56+
57+
2. **Savepoints**: You can set savepoints within a transaction to mark points where you can rollback to if necessary.
58+
59+
```java
60+
try {
61+
connection.setAutoCommit(false); // Disable auto-commit
62+
// Execute SQL statements
63+
Savepoint savepoint = connection.setSavepoint("savepoint1"); // Set savepoint
64+
// More SQL statements
65+
connection.rollback(savepoint); // Rollback to savepoint
66+
connection.commit(); // Commit transaction
67+
} catch (SQLException e) {
68+
e.printStackTrace();
69+
try {
70+
connection.rollback(); // Rollback transaction if an exception occurs
71+
} catch (SQLException ex) {
72+
ex.printStackTrace();
73+
}
74+
} finally {
75+
try {
76+
connection.setAutoCommit(true); // Enable auto-commit
77+
} catch (SQLException ex) {
78+
ex.printStackTrace();
79+
}
80+
}
81+
```
82+
83+
### Note:
84+
85+
- Always handle exceptions properly and close resources in a finally block to ensure proper cleanup.
86+
- Use PreparedStatement to prevent SQL injection attacks and improve performance.
87+
- Transactions are typically used when you need to execute multiple SQL statements as a single unit of work, ensuring data consistency.
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
2+
3+
## Introduction to JDBC
4+
5+
Java Database Connectivity (JDBC) is a Java API for connecting and interacting with relational databases from Java programs. It provides a standard interface for Java applications to access databases, execute SQL queries, and manipulate database data.
6+
7+
### Key Components of JDBC
8+
9+
1. **Driver Manager**: Manages a list of database drivers. It is responsible for loading the appropriate driver based on the database URL provided by the application.
10+
11+
2. **Driver**: Implements the JDBC interfaces to communicate with a specific type of database. Each database vendor provides its own JDBC driver.
12+
13+
3. **Connection**: Represents a connection to a database. It is used to establish communication with the database and provides methods for executing SQL statements.
14+
15+
4. **Statement**: Represents an SQL statement to be executed against the database. It can be a simple statement, a prepared statement, or a callable statement.
16+
17+
5. **ResultSet**: Represents the result of a query executed against the database. It provides methods for navigating through the rows of the result set and retrieving column values.
18+
19+
### Steps to Use JDBC
20+
21+
1. **Load the Driver**: Register the JDBC driver using `Class.forName()` or let the DriverManager automatically load the appropriate driver.
22+
23+
2. **Establish Connection**: Create a connection to the database using `DriverManager.getConnection()` method by providing the database URL, username, and password.
24+
25+
3. **Create Statement**: Create a Statement object using the connection to execute SQL queries.
26+
27+
4. **Execute Query**: Execute SQL queries using the Statement object. For example, `executeQuery()` for SELECT queries and `executeUpdate()` for INSERT, UPDATE, DELETE queries.
28+
29+
5. **Process Results**: Process the results returned by the query using the ResultSet object.
30+
31+
6. **Close Resources**: Close the ResultSet, Statement, and Connection objects when they are no longer needed to release database resources.
32+
33+
### Example Code Snippet
34+
35+
```java
36+
import java.sql.*;
37+
38+
public class JDBCDemo {
39+
public static void main(String[] args) {
40+
try {
41+
// Load the driver
42+
Class.forName("com.mysql.cj.jdbc.Driver");
43+
44+
// Establish connection
45+
String url = "jdbc:mysql://localhost:3306/mydatabase";
46+
String username = "username";
47+
String password = "password";
48+
Connection connection = DriverManager.getConnection(url, username, password);
49+
50+
// Create statement
51+
Statement statement = connection.createStatement();
52+
53+
// Execute query
54+
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");
55+
56+
// Process results
57+
while (resultSet.next()) {
58+
int id = resultSet.getInt("id");
59+
String name = resultSet.getString("name");
60+
double salary = resultSet.getDouble("salary");
61+
System.out.println("ID: " + id + ", Name: " + name + ", Salary: " + salary);
62+
}
63+
64+
// Close resources
65+
resultSet.close();
66+
statement.close();
67+
connection.close();
68+
} catch (ClassNotFoundException | SQLException e) {
69+
e.printStackTrace();
70+
}
71+
}
72+
}
73+
```
74+
75+
### JDBC Drivers
76+
77+
There are four types of JDBC drivers:
78+
79+
1. **Type 1 (JDBC-ODBC Bridge)**: Uses ODBC (Open Database Connectivity) to connect to databases. It requires native code and is platform-dependent.
80+
81+
2. **Type 2 (Native-API Driver)**: Uses a database-specific native library to communicate with the database. It is platform-dependent and requires native code.
82+
83+
3. **Type 3 (Network Protocol Driver)**: Communicates with a middle-tier server using a database-independent protocol, which then communicates with the database. It is platform-independent but requires additional software.
84+
85+
4. **Type 4 (Thin Driver, JDBC Net Pure Java Driver)**: Communicates directly with the database using a pure Java implementation. It is platform-independent and does not require additional software.
86+
87+
### Conclusion
88+
89+
JDBC provides a powerful and flexible API for Java applications to interact with relational databases. By following the JDBC architecture and using appropriate drivers, developers can easily connect to databases, execute SQL queries, and manage database data from their Java programs.

0 commit comments

Comments
 (0)