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

oop-database-connectivity

The document provides a detailed explanation of Java database connectivity using MySQL, including code snippets for establishing a connection, executing SQL queries, and handling results. It covers the initialization of connection variables, the use of JDBC driver, and the execution of a SQL query to retrieve data from a 'student' table. Additionally, it emphasizes the importance of closing database resources to prevent memory leaks and potential issues.

Uploaded by

chandsajid6522
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

oop-database-connectivity

The document provides a detailed explanation of Java database connectivity using MySQL, including code snippets for establishing a connection, executing SQL queries, and handling results. It covers the initialization of connection variables, the use of JDBC driver, and the execution of a SQL query to retrieve data from a 'student' table. Additionally, it emphasizes the importance of closing database resources to prevent memory leaks and potential issues.

Uploaded by

chandsajid6522
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

lOMoARcPSD|43637079

OOP database connectivity

Fundamental of Programming (Khawaja Fareed University of Engineering and


Information Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Faheem Abdullah ([email protected])
lOMoARcPSD|43637079

OOP PRESENTATION - JAVA


Database connectivity with MySQL
/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package javaapplication1;

import java.sql.*;

/**

* @author Dr. Abdul Sattar

*/

public class JavaApplication1 {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

The line Connection connection = null; declares a variable named connection of type
Connection and initializes it to null.It declares a variable named connection of type
Connection. This variable will be used to store a reference to a Connection object.

Connection connection = null;

try {

// below two lines are used for connectivity.

This line dynamically loads the MySQL JDBC driver class into memory.Loading the driver
class is necessary to register it with the DriverManager so that it can be used to establish a

Downloaded by Faheem Abdullah ([email protected])


lOMoARcPSD|43637079

connection to the database.

Class.forName("com.mysql.jdbc.Driver");

This line establishes a connection to the MySQL database. Let's break down the parameters:

"jdbc:mysql://localhost:3306/test": This is the JDBC URL that specifies the type of database
(mysql), the host (localhost), the port (3306), and the database name (test). This URL format
is standard for MySQL databases.

"root": This is the username used to authenticate the connection. In this case, it is set to the
default MySQL root user. In a production environment, it's recommended to use a dedicated
user with restricted privileges.

"": This is the password used to authenticate the connection. In the provided code, an empty
string is used as the password. In practice, using an empty string for the password is not
secure. In a production environment, you should use a strong and secure password.

The getConnection method returns a Connection object, which is assigned to the variable
connection. This Connection object is used to interact with the database

connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test",

"root", "");

// mydb is database

// mydbuser is name of database

// mydbuser is password of database

Here, a variable named statement is declared with the data type Statement. However, it's not
initialized yet.

Statement statement;

This line creates a Statement object by calling the createStatement() method on the
Connection object (connection). The createStatement() method is provided by the
Connection interface in JDBC. It returns a new Statement object associated with the given
connection.

The Statement object (statement) is then ready to be used to execute SQL queries against
the connected database (test in this case).

statement = connection.createStatement();

Declaration: ResultSet resultSet; declares a variable named resultSet of type ResultSet. This
is where the results of the SQL query will be stored.

Execution of SQL Query:

Downloaded by Faheem Abdullah ([email protected])


lOMoARcPSD|43637079

statement is an object of the Statement interface, which is used to execute SQL queries.

statement.executeQuery("select * from student"); executes the SQL query "select * from


student".

The query select * from student retrieves all columns (*) from the "student" table.

Result Set Assignment:

The result of the query is returned as a ResultSet object.

resultSet = ... assigns this ResultSet object to the previously declared resultSet variable.

ResultSet resultSet;

resultSet = statement.executeQuery( "select * from student");

int id;

String name;

This line checks if there is another row in the result set. resultSet.next() returns true if there
is another row, and the loop continues. If there are no more rows, it returns false, and the
loop exits.

while (resultSet.next())

Within the loop, this line retrieves the value of the "id" column from the current row of the
result set and stores it in the variable id. It assumes that the "id" column is of type integer in
the database.

id = resultSet.getInt("id");

This line retrieves the value of the "name" column from the current row of the result set and
stores it in the variable name. The trim() method is used to remove any leading or trailing
whitespaces from the retrieved string.

name = resultSet.getString("name").trim();

Finally, this line prints the values of id and name to the console. It prints a formatted string
that includes the ID and Name values for each row in the result set.

System.out.println("ID : " + id + " Name : " + name);

The ResultSet object (resultSet) holds the result of the executed SQL query.

Downloaded by Faheem Abdullah ([email protected])


lOMoARcPSD|43637079

Closing the ResultSet is essential to release its associated resources and free up memory. It
also ensures that the cursor pointing to the current row of data is closed.

resultSet.close();

The Statement object (statement) is responsible for executing SQL queries.

Closing the Statement is important to release resources tied to the execution of SQL
statements. It also helps prevent potential memory leaks.

statement.close();

The Connection object (connection) represents the connection to the database.

Closing the Connection is crucial to release database-related resources, such as network


connections and database locks. It also ensures that the connection is properly terminated.

connection.close();

catch (Exception e): This line specifies that the following block of code will be executed if an
exception of type Exception (which is a generic exception type) is thrown within the
corresponding try block.

System.out.println("some thing went wrong" + e.getMessage()): This line prints an error


message to the console. It concatenates the string "some thing went wrong" with the error
message obtained from the exception (e.getMessage()).

e.getMessage() retrieves the detail message string associated with the exception. It provides
more information about the nature of the exception.

catch (Exception e)

System.out.println("some thing went wrong" + e.getMessage());

Downloaded by Faheem Abdullah ([email protected])

You might also like