-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDemo1.java
More file actions
78 lines (68 loc) · 2.33 KB
/
Demo1.java
File metadata and controls
78 lines (68 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Step -1 Load the Driver (Loading a Class)
String driverName = "com.mysql.jdbc.Driver";
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("com.mysql.jdbc.Driver");
// Driver is loaded because we need to communicate to the database
// driver can talk to the lowlevel database things
// driver is high level thing
Class.forName(driverName);
// Step -2 Create Connection
// Default Port no for Oracle is 1521
// jdbc:oracle:thin:@ipaddress:portno:dbname
// mysql Default Port No 3306
// jdbc:mysql://hostname:port/dbname
boolean isFound = false;
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the Salary");
String entersalary = scanner.nextLine();
System.out.println("Enter the Name");
String name = scanner.nextLine();
String dbURL = "jdbc:mysql://localhost:3306/mydb";
String userid = "root";
String password = "amit123456";
Connection con = DriverManager.getConnection(dbURL,userid,password);
if(con!=null){
System.out.println("Connection Created...");
}
// Step-3 DO Query and Get the Result
// ? is a PlaceHolder
PreparedStatement pstmt = con
.prepareStatement
("select id ,name ,salary from employee"
+ " where salary>? and name=?");
// I am Setting the 1st ? Value
pstmt.setDouble(1, Double.parseDouble(entersalary));
pstmt.setString(2, name);
ResultSet rs = pstmt.executeQuery();
//Statement stmt = con.createStatement();
// NO SQL Injection Prevention
//ResultSet rs =
// stmt.executeQuery
// ("select id,name,salary from employee where salary>"+entersalary);
// Step -4 Traverse the ResultSet
// rs.next() return true if there is a Row in ResultSet
while(rs.next()){
isFound = true;
System.out.println(rs.getInt("id")+" "
+rs.getString("name")+" "+rs.getDouble("salary"));
}
if(!isFound){
System.out.println("No Record Found...");
}
// Step -5 Close all the open resources
// What Ever is open last must be close first
rs.close();
pstmt.close();
//stmt.close();
con.close();
}
}