-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDAO.java
More file actions
91 lines (57 loc) · 1.91 KB
/
DAO.java
File metadata and controls
91 lines (57 loc) · 1.91 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
79
80
81
82
83
84
85
86
87
88
89
90
91
package jdbc;
import java.sql.*;
class Student{
int rollNo;
String sname;
@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", sname=" + sname + "]";
}
public Student() {
}
public Student(int rollNo, String sname) {
this.rollNo = rollNo;
this.sname = sname;
}
}
public class DAO {
public static void main(String[] args) throws Exception {
StudentDAO dao = new StudentDAO();
//Add data.
Student std = new Student(11,"Mike");
dao.addStudent(std);
//Fetch data.
System.out.println(dao.getStudent(11));
//Delete data.
dao.removeStudent(11);
}
}
class StudentDAO{
Student getStudent(int rollNo) throws Exception {
Student std = new Student();
std.rollNo = rollNo;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "root123");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select sname from student where rollNo=" + rollNo);
rs.next();
std.sname = rs.getString("sname");
return std;
}
void addStudent(Student std) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "root123");
PreparedStatement pst = con.prepareStatement("insert into student values (?,?)");
pst.setInt(1, std.rollNo);
pst.setString(2, std.sname);
int n = pst.executeUpdate();
System.out.println(n + "row/s affected.. addStudent");
}
void removeStudent(int rollNo) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "root123");
Statement st = con.createStatement();
int n = st.executeUpdate("delete from student where rollNo = " + rollNo);
System.out.println(n+ "row/s affected.. removeStudent");
}
}