Skip to content

Commit 181a8df

Browse files
committed
feat(jdbc-sqlite): add interactive query execution with user input in Statements.java
What - Added `Statements.java` under Section28JDBCusingSQLite package. - Demonstrates executing parameterized SELECT queries using `PreparedStatement`. - Integrated `Scanner` to allow dynamic `deptno` input from the user. - Prints student records in a formatted structure or informs when no records are found. Why - Highlights secure and flexible query execution by combining JDBC with user input. - Avoids SQL injection by binding parameters via `PreparedStatement` instead of string concatenation. - Improves user experience with real-time query input/output. - Shows practical usage of `ResultSet.isBeforeFirst()` to detect empty results. How - Setup: - Loaded SQLite JDBC driver with `Class.forName("org.sqlite.JDBC")`. - Established connection to `univ.db` SQLite database. - Execution: - Prepared query: `select * FROM students where deptno=?`. - Prompted user for a department number (`deptno`) via `Scanner`. - Bound parameter dynamically using `pstm.setInt(1, dno)`. - Executed query with `executeQuery()`. - Output: - Checked if any records exist with `rs.isBeforeFirst()`. - Iterated through `ResultSet`, printing student details (roll, name, city, deptno). - Displayed "record not found" if no matching rows exist. - Cleanup: - Closed `PreparedStatement` and connection to release resources. Key Notes - `PreparedStatement` ensures safer, cleaner, and reusable SQL queries. - `isBeforeFirst()` is useful for detecting empty results without iterating. - Scanner allows runtime interaction with the database, simulating real-world applications. - Example output format: `101 | Alice | Delhi | 10 |` Real-life Applications - University management systems: fetch students by department dynamically. - Employee systems: filter employees by department, branch, or role. - Banking apps: query transactions by account/branch ID. - Interactive console-based reporting tools for admins. Future Improvements - Add error handling for invalid input (e.g., non-numeric deptno). - Implement try-with-resources for automatic cleanup of JDBC objects. - Enhance output formatting into tabular form for readability. - Extend functionality to allow updates, inserts, and deletes via user input. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent b2f1a1e commit 181a8df

File tree

1 file changed

+80
-31
lines changed
  • Section28JDBCusingSQLite/JAVA SQL Interfaces/Prepared Statements/src

1 file changed

+80
-31
lines changed
Lines changed: 80 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,17 @@
1-
//it is an interface.
2-
//We don't create the obj we create the obj of the
3-
//statement using connection. we handle it using references.
4-
// Statement = createstatement(); //obj of statement we are creating here.
5-
6-
// stm.executeQuery(select * from students);
7-
// stm.executeuppdate("DML: ");
8-
9-
//Three types of statements:
10-
11-
//Statement
12-
//PreparedStatement:
13-
//How to create prep statement();
14-
//Prep statement execute multiple times by changing thr parameter.
15-
16-
17-
//Callable statement: used fot invoking a stored procedures.
18-
//In some databases they support some program along with a database.
19-
20-
211
import java.sql.*;
222
import java.util.Scanner;
233

244
public class Statements {
255
public static void main(String[] args)throws Exception {
266
Class.forName("org.sqlite.JDBC");
27-
//Invoke drivers
7+
//Invoke drivers.
288

299
//Connection is Establish.
30-
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/sqlite/univ.db");
31-
System.out.println("✅ Connection Established!");
10+
// Connection is Established.
11+
Connection con = DriverManager.getConnection(
12+
"jdbc:sqlite:/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section28JDBCusingSQLite/univ.db"
13+
);
14+
System.out.println("Connection Established!");
3215

3316
PreparedStatement pstm = con.prepareStatement("select * FROM students where deptno=?");
3417

@@ -53,16 +36,82 @@ public static void main(String[] args)throws Exception {
5336
}
5437
}
5538

56-
// / 7. Check if any records were found
57-
// boolean recordFound = false;
39+
/* 7. Check if any records were found */
40+
boolean recordFound = false;
5841

59-
// // 8. If no records were found, print a message
60-
// if (!recordFound) {
61-
// System.out.println("❌ No records found for deptno = " + dno);
62-
// }
42+
// 8. If no records were found, print a message
43+
/*
44+
if (!recordFound) {
45+
System.out.println("❌ No records found for deptno = " + dno);
46+
}
47+
*/
6348

6449
pstm.close(); //close the statement.
6550
pstm.close(); //Connection close.
66-
System.out.println("Connection Closed.");
51+
System.out.println("Connection Closed.");
6752
}
68-
}
53+
}
54+
55+
/*
56+
It is an interface.
57+
We don't create the object directly, we create the object of the Statement using Connection. We handle it using references.
58+
59+
Statement stm = con.createStatement(); // obj of statement we are creating here.
60+
61+
stm.executeQuery("select * from students");
62+
stm.executeUpdate("DML: ");
63+
64+
Three types of Statements:
65+
1. Statement
66+
- Normal queries run karne ke liye.
67+
68+
2. PreparedStatement
69+
- How to create: con.prepareStatement();
70+
- PreparedStatement execute multiple times by changing the parameter.
71+
72+
3. CallableStatement
73+
- Used for invoking a stored procedure.
74+
- In some databases, they support some programs along with a database.
75+
*/
76+
77+
/*
78+
1. JDBC Driver Load:
79+
- `Class.forName("org.sqlite.JDBC");`
80+
- Isse SQLite JDBC driver memory me load ho jaata hai.
81+
✔ Without driver, Java ko DB samajh hi nahi aayega.
82+
83+
2. Connection Establishes:
84+
- `DriverManager.getConnection("jdbc:sqlite:...univ.db")`
85+
- SQLite database `univ.db` ke saath connection establish ho jaata hai.
86+
✔ Ye bridge hai Java program aur DB ke beech.
87+
88+
3. PreparedStatement:
89+
- `PreparedStatement pstm = con.prepareStatement("select * FROM students where deptno=?");`
90+
- Yaha query pre-compiled hoti hai aur hum `?` ke jagah runtime par values inject karte hain.
91+
✔ SQL injection avoid karne ke liye safe hai.
92+
93+
4. Input from User:
94+
- Scanner se dept number input liya jaata hai (`dno`).
95+
- `pstm.setInt(1, dno);` → query me pehle `?` ke jagah deptno daal diya.
96+
97+
5. Execute Query:
98+
- `ResultSet rs = pstm.executeQuery();`
99+
- Database se matching rows return hoti hain.
100+
101+
6. ResultSet Handling:
102+
- `isBeforeFirst()` → check karta hai ki ResultSet empty hai ya nahi.
103+
- Agar records mile → loop me har row ke `roll`, `name`, `city`, `deptno` print ho jaate hain.
104+
105+
7. Closing:
106+
- `pstm.close();`
107+
- `con.close();` (tumhare code me galti se `pstm.close()` do baar likha hai – ek baar `con.close()` hona chahiye).
108+
✔ Always close resources to free DB locks and memory.
109+
110+
✔ Program SQLite database ke `students` table se records fetch karta hai.
111+
✔ User se deptno input leta hai aur sirf us deptno wale students ko print karta hai.
112+
✔ PreparedStatement safe hai (SQL injection nahi hoga).
113+
✔ Properly connection close karke resources release kiye jaate hain.
114+
115+
Ye ek search utility hai. Tum department number enter karte ho, aur program database ke students table me se us
116+
department ke sabhi students ki details print kar deta hai (roll, name, city, deptno).
117+
*/

0 commit comments

Comments
 (0)