Exercise-9
A) Write a java program that connects to a database using JDBC program
AIM: To Write a java program that connects to a database using JDBC program
DESCRIPTION:
The Java code demonstrates how to establish a connection to an SQLite database using
JDBC (Java Database Connectivity). It begins by importing the necessary Connection and
DriverManager classes from the [Link] package. The main method defines a string variable url
that contains the absolute path to the SQLite database ([Link]), located on the D drive of the
system.
Within the try block, the [Link](url) method is called to establish a
connection to the SQLite database using the provided URL. If the connection is successful, a
confirmation message, "Connection to SQLite established," is printed to the console. After that, the
connection is closed using [Link](), and a message, "Connection closed," is displayed.
In case of an error (such as if the database is not found or the URL is incorrect), the code
catches the exception and prints an error message detailing the issue. This structure ensures that
any problems are handled gracefully and provides feedback about the status of the database
connection.
Source code:
import [Link];
import [Link];
public class DatabaseConnection{
public static void main(String[] args) {
// Use absolute path for the SQLite database
String url = "jdbc:sqlite:D:/waris/java/[Link]";
try {
// Establish a connection to the database
Connection conn = [Link](url);
[Link]("Connection to SQLite established.");
// Close the connection
[Link]();
[Link]("Connection closed.");
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
Compile: javac -cp [Link] [Link]
Run: java --enable-native-access=ALL-UNNAMED -cp .;[Link]
DatabaseConnection
OUTPUT:
RESULT:
Java program that connects to a database using JDBC program has been done successfully.
B) Write a java program to connect to database using JDBC & insert values into table
AIM: To write a java program to connect to database using JDBC & insert values into table
DESCRIPTION:
The Java code demonstrates a basic workflow for interacting with an SQLite database using
JDBC (Java Database Connectivity). The program connects to a SQLite database located at
D:/waris/java/[Link] using the [Link]() method. Once the
connection is established, a Statement object is created to execute SQL commands.
The first SQL command executed creates a table named students with three columns: id (an
integer primary key), name (a non-null text field), and age (an integer). The table creation is
safeguarded by the IF NOT EXISTS clause, ensuring that it won't be recreated if it already exists.
After successfully creating the table, the code inserts sample data for two students (Alice and Bob)
using an INSERT SQL statement.
Next, a SELECT query is executed to retrieve the id, name, and age of all students from the
students table. The results are retrieved in a ResultSet, and a while loop iterates over each record,
printing the student details to the console.
Finally, the code closes the ResultSet, Statement, and Connection objects to release
database resources and ensure proper cleanup. If an exception occurs at any point, the program
catches it and prints an error message. Overall, this code showcases the process of establishing a
database connection, performing CRUD operations (Create, Read), and closing resources properly
in a SQLite database environment.
SOURCE CODE:
import [Link];
import [Link];
import [Link];
import [Link];
public class DatabaseExample{
public static void main(String[] args) {
// Use absolute path for the database
String url = "jdbc:sqlite:D:/waris/java/[Link]";
try {
// Establish a connection to the database
Connection conn = [Link](url);
[Link]("Connection to SQLite established.");
// Create a statement object to execute SQL queries
Statement stmt = [Link]();
// Create a table
String createTableSQL = "CREATE TABLE IF NOT EXISTS students (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INTEGER)";
[Link](createTableSQL);
[Link]("Table created successfully.");
// Insert data into the table
String insertSQL = "INSERT INTO students (name, age) VALUES ('Alice', 20), ('Bob', 22)";
[Link](insertSQL);
[Link]("Data inserted successfully.");
// Query the table
String selectSQL = "SELECT id, name, age FROM students";
ResultSet rs = [Link](selectSQL);
// Display the results
[Link]("Students in the database:");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
// Close resources
[Link]();
[Link]();
[Link]();
[Link]("Connection closed.");
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
Compile: javac -cp [Link] [Link]
Run: java --enable-native-access=ALL-UNNAMED -cp .;[Link]
DatabaseExample
OUTPUT:
RESULT:
Java program to connect to database using JDBC & insert values into table has been done
successfully.
C) Write a java program to connect to a database using JDBC and delete values from table.
AIM:To write a java program to connect to a database using JDBC and delete values from table.
DESCRIPTION:
This Java program demonstrates how to connect to an SQLite database using JDBC, ensure
the presence of a table, and perform operations like data deletion and querying. The program
begins by establishing a connection to the SQLite database located at D:/waris/java/[Link].
Once the connection is successful, it creates a Statement object for executing SQL queries. The
program first checks if the students table exists and creates it if it does not. This is done using the
CREATE TABLE IF NOT EXISTS SQL command to ensure that the table is available for the
delete operation. The program then executes a DELETE SQL statement to remove records from the
students table where the student’s name is "Alice".
After performing the delete operation, the program proceeds to display the remaining
records in the students table using a SELECT SQL query. It uses the ResultSet object to iterate
through and print out the id, name, and age of the remaining students. This is done to verify that the
deletion was successful. Finally, the program closes the ResultSet, Statement, and Connection
objects to free up resources. If an error occurs at any point, the program catches the exception and
prints the error message, helping with debugging. This structure ensures that database operations
are performed correctly, and resources are managed efficiently throughout the program.
SOURCE CODE:
import [Link];
import [Link];
import [Link];
import [Link];
public class DatabaseDeleteExample {
public static void main(String[] args) {
// Use absolute path for the database
String url = "jdbc:sqlite:D:/waris/java/[Link]";
try {
// Establish a connection to the database
Connection conn = [Link](url);
[Link]("Connection to SQLite established.");
// Create a statement object to execute SQL queries
Statement stmt = [Link]();
// Make sure the table exists before performing the delete operation
String createTableSQL = "CREATE TABLE IF NOT EXISTS students (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INTEGER)";
[Link](createTableSQL);
[Link]("Table 'students' checked/created.");
// Delete data from the table where the condition matches (e.g., delete the student named
'Alice')
String deleteSQL = "DELETE FROM students WHERE name = 'Alice'";
int rowsAffected = [Link](deleteSQL);
if (rowsAffected > 0) {
[Link]("Data deleted successfully.");
} else {
[Link]("No records found to delete.");
}
// Query the table to display the remaining records
String selectSQL = "SELECT id, name, age FROM students";
ResultSet rs = [Link](selectSQL);
[Link]("Students in the database after deletion:");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
// Close resources
[Link]();
[Link]();
[Link]();
[Link]("Connection closed.");
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
Compile: javac -cp [Link] [Link]
Run: java --enable-native-access=ALL-UNNAMED -cp .;[Link]
DatabaseDeleteExample
OUTPUT:
RESULT:
Java program to connect to a database using JDBC and delete values from table has been done
successfully.