0% found this document useful (0 votes)
12 views

JDBC

The document discusses JDBC and its key concepts. JDBC provides a standard interface for Java programs to connect to databases and perform CRUD operations. It covers drivers, connections, statements, result sets, and the DriverManager class. The Connection interface represents a connection to a database and allows executing statements and handling transactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

JDBC

The document discusses JDBC and its key concepts. JDBC provides a standard interface for Java programs to connect to databases and perform CRUD operations. It covers drivers, connections, statements, result sets, and the DriverManager class. The Connection interface represents a connection to a database and allows executing statements and handling transactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Jdbc by ashish

27 June 2023 11:22

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 )

some key concepts and components related to JDBC:


1. Driver: A JDBC driver is a software component that enables Java applications to
connect and communicate with a specific database management system (DBMS).
There are four types of JDBC drivers: JDBC-ODBC Bridge Driver, Native API Driver,
Network Protocol Driver, and Thin Driver. Each driver type follows a different
approach for establishing a connection to the database.
2. Connection: A connection represents a communication link between a Java
application and a database. It allows you to establish a session with the database
server and perform various operations such as executing SQL statements and
managing transactions.
3. Statement: A statement is an interface provided by JDBC that allows you to execute
SQL queries or updates in the database. It can be either a Statement (for general
SQL statements), a PreparedStatement (for pre-compiled SQL statements with
parameters), or a CallableStatement (for executing stored procedures).
4. ResultSet: A ResultSet represents the result of a database query. It provides
methods to retrieve and manipulate the data returned by the SQL statement. You
can navigate through the result set, retrieve individual columns, and perform
operations on the data.
5. DriverManager: The DriverManager class is responsible for managing the JDBC
drivers. It helps in loading the appropriate driver based on the database URL
provided and establishing a connection to the database.

New Section 3 Page 1


To establish a connection using JDBC, you need to follow these steps:
6. Load the JDBC driver: Before establishing a connection, you need to load the
appropriate JDBC driver class. This is typically done using the Class.forName()
method, passing the fully qualified name of the driver class as a parameter.
However, as mentioned earlier, in newer versions of Java and with most JDBC
drivers, this step may not be necessary.
7. Define the connection URL: The connection URL specifies the location and other
details required to connect to the database. The URL format depends on the specific
database and JDBC driver you are using. Consult the documentation of your
database and driver for the correct URL format. Example:
jdbc:mysql://localhost:3306/mydatabase
8. Provide authentication credentials: You need to provide the necessary authentication
credentials, such as a username and password, to establish the connection. These
credentials are typically passed as parameters when calling the
DriverManager.getConnection() method.
9. Establish the connection: Use the DriverManager.getConnection() method to
establish the connection to the database. Pass the connection URL and
authentication credentials as parameters. This method returns a Connection object
representing the connection.
10. Create a statement: Once the connection is established, you can create a statement
object using the createStatement() method of the Connection object. This statement
object allows you to execute SQL queries, updates, or stored procedures on the
database.
11. Execute SQL queries or updates: Use the statement object to execute SQL queries
or updates by calling the appropriate methods such as executeQuery() for SELECT
queries or executeUpdate() for INSERT, UPDATE, or DELETE statements. These
methods return a ResultSet or the number of affected rows, respectively.
12. Process the results: If you executed a query that returns data, you can process the
retrieved results using the ResultSet object. You can iterate over the result set,
retrieve column values, and perform operations on the data.
13. Close resources: It's important to close the resources properly to free up system
resources and avoid memory leaks. Close the ResultSet, Statement, and Connection
objects in reverse order of creation.

New Section 3 Page 2


objects in reverse order of creation.

The `Connection` interface in JDBC represents a connection to a specific database. It provides


methods for establishing a connection, managing transactions, creating statements, and handling
various database operations. Here are some important aspects of the `Connection` interface:

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.

Handling Database Operations:


- The `Connection` interface provides methods to handle various database operations, including
executing SQL statements, retrieving metadata, and managing database properties.
- You can execute SQL statements using the created statements (`Statement`, `PreparedStatement`,
or `CallableStatement`) and process the results using `ResultSet` objects.
- `getMetaData()` returns a `DatabaseMetaData` object that provides information about the
database.
- `setAutoCommit()`, `commit()`, and `rollback()` are used for transaction management.
- Other methods include `setReadOnly()`, `setTransactionIsolation()`, `setSchema()`, and more, for
configuring and managing the connection.

New Section 3 Page 3


Closing the Connection:
- It's important to close the `Connection` object once you're done with it to release system
resources.
- Use the `close()` method on the `Connection` object to close the connection.
- Closing the connection also implicitly closes any associated statements, result sets, and other
resources.

Here's an example showcasing the basic usage of the `Connection` interface:

```java
import java.sql.*;

public class ConnectionExample {


public static void main(String[] args) {
Connection connection = null;

try {
// Establish the connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");

// Execute SQL statements


Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");

// Process the result set


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

// 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.

New Section 3 Page 4


JDBC DriverManager
It is a very crucial component of the JDBC. The main work of the DriverManager is to
load a specific driver for a database as various databases may have a different
driver. The driver manager ensures that the correct driver is chosen for the database
we are interacting with and is returned to the application.

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.

New Section 3 Page 5


Complied at once..
disAdv : it can take one query at a time and complied it if we want to execute query again then we
have to create another pre statement.

Class.forName("com.example.MyClass") loads the class com.example.MyClass. If


the class is found and successfully loaded, it initializes the class and returns a Class
object representing it.
The ClassNotFoundException is thrown if the class specified in the parameter is not
found. It's important to handle this exception to avoid runtime errors.
Class.forName() is commonly used in JDBC programming to load the JDBC driver
class dynamically. For example, if you're using a MySQL database, you would load
the MySQL JDBC driver using Class.forName("com.mysql.jdbc.Driver") before
establishing a connection.
It's worth noting that in newer versions of Java (since Java SE 6), when using JDBC,
explicitly calling Class.forName() is not necessary for most JDBC drivers. The JDBC
driver class is automatically loaded and registered with DriverManager when the
driver JAR is present on the classpath. However, in some cases or with older JDBC
drivers, you may still need to use Class.forName() explicitly to load the driver class.

New Section 3 Page 6

You might also like