Connection to Database

Connection to Database

To connect to a database using JDBC, you need to follow these steps:

Load the JDBC driver: Before you can connect to a database, you need to load the JDBC driver for your database. The driver class name and the database URL are used to load the driver. For example, to load the MySQL driver, you would use the following code:

Class.forName(“com.mysql.jdbc.Driver”);

Establish a connection: Once you have loaded the JDBC driver, you can establish a connection to the database using the DriverManager.getConnection() method. This method takes the database URL, username, and password as arguments. For example:

String url = “jdbc:mysql://localhost:3306/mydatabase”;

String username = “myuser”;

String password = “mypassword”;

Connection connection = DriverManager.getConnection(url, username, password);

Create a statement: After you have established a connection, you can create a Statement object using the Connection.createStatement() method. This object is used to execute SQL statements against the database. For example:

Statement statement = connection.createStatement();

Execute SQL statements: You can execute SQL statements using the Statement.execute() method. This method returns a boolean value indicating whether the statement executed successfully or not. For example:

boolean success = statement.execute(“SELECT * FROM mytable”);

Process the results: If the SQL statement you executed returns results, you can process them using the ResultSet object returned by the Statement.executeQuery() method. This object represents a set of rows retrieved from the database. For example:

ResultSet resultSet = statement.executeQuery(“SELECT * FROM mytable”);

while (resultSet.next()) {

    int id = resultSet.getInt(“id”);

    String name = resultSet.getString(“name”);

    System.out.println(id + “, ” + name);

}

Close the connection: Once you have finished using the database connection, you should close it using the Connection.close() method. For example: connection.close();

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

JDBC
Types of Statements

Get industry recognized certification – Contact us

keyboard_arrow_up