JDBC
JDBC
JDBC stands for Java Database Connectivity, and it is an API (Application Programming Interface) that
provides a standard way for Java programs to interact with relational databases. It allows developers
to perform various database operations such as querying data, updating records, inserting new data,
and executing stored procedures. (Crud )
Establishing a Connection:
- The connection to the database is typically established using the `DriverManager.getConnection()`
method, which takes the database URL, username, and password as parameters.
- The database URL specifies the location and other details required to connect to the database.
- Example: `Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");`
Managing Transactions:
- The `Connection` interface supports transaction management through methods like `commit()`,
`rollback()`, and `setAutoCommit()`.
- By default, each SQL statement is treated as a separate transaction (auto-commit mode). You can
disable auto-commit mode using `setAutoCommit(false)`, and then explicitly commit or rollback the
transaction as needed.
Creating Statements:
- The `Connection` interface provides methods for creating different types of statements:
`createStatement()`, `prepareStatement()`, and `prepareCall()`.
- `createStatement()` creates a `Statement` object for executing simple SQL queries and updates.
- `prepareStatement()` creates a `PreparedStatement` object for executing parameterized SQL
queries.
- `prepareCall()` creates a `CallableStatement` object for executing stored procedures.
```java
import java.sql.*;
try {
// Establish the connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
// Close resources
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the connection
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
Remember to handle exceptions properly and close the resources and connections to avoid memory
leaks and ensure proper cleanup.
Statement st = con.CreateStatement();
St.execute();
We have only obj for excuting any numbers queries.
Dis avd : For every querty the statement obj get complied and executed.