封装
BaseDao
传参数,数量、类型不固定怎么办?
public class TestMethod {
//第一种,方法的重载
/*public int sum(int a) {
return a;
}
public int sum(int a,int b) {
return a+b;
}
public int sum(int a,int b,int c) {
return a+b+c;
}*/
//方法2,放入一个数组
/*public int sum(int [] arr) {
int s=0;
for(int i:arr) {
s+=i;
}
return s;
}
public static void main(String[] args) {
int [] arr= {12,23};
new TestMethod().sum(arr);
}*/
//方法3,可变长度的参数
//一个方法中只能有一个可变长度参数
//可变长度参数只能放在最后一个位置
public int sum(int ...arr) {
int s=0;
for(int i:arr) {
s+=i;
}
return s;
}
public static void main(String[] args) {
new TestMethod().sum();
new TestMethod().sum(100);
new TestMethod().sum(100,200);
}
}
数据库的封装
数据库连接封装
public Connection getConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@//localhost:1521/ORCL";
String user = "scott";
String password = "123";
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("数据库驱动不见了");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("连接失败"+e.getMessage());
}
}
增删改的封装
public static void main(String[] args) throws SQLException {
Scanner input=new Scanner(System.in);
System.out.println("员工号");
int empno=input.nextInt();
System.out.println("工资");
int sal=input.nextInt();
String sql="update emp set sal=sal+? where empno=?";
int rows=new BaseDao().executeUpdate(sql,sal,empno);
if(rows>0) {
System.out.println("加薪成功");
}
else {
System.out.println("不成功");
}
}
public int executeUpdate(String sql,Object ...args) {
try {
Connection conn=this.getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
if(args!=null) {
for(int i=0;i
查询的封装
public ResultSet executeQuery(String sql,Object ... args) {
try {
Connection conn=this.getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
if(args!=null) {
for(int i=0;i
对象的封装
create table grade(gradeId number(10),gradeName varchar2(30) not null);
create table students(stuid number(10) not null,stuname varchar2(30),gender varchar2(2),gradeid number(10),phone varchar2(20),address varchar2(50));
alter table grade add constraint pk_gradeid primary key(gradeid);
alter table students add constraint fk_gradeid foreign key(gradeid) references grade(gradeId);
alter table students add constraint ck_gender check(gender='男' or gender='女');
insert into grade values(100,'计算机科学与技术');
insert into students values(10001,'李玉','男',100,'19987260835','河南省许昌市');
create sequence sql_students_stuid
increment by 1
start with 10000;
alter table students
add constraint uq_stuname unique(stuname);--唯一约束
Dao数据访问对象
工具类 BaseDao 封装执行sql语句的常用方法
实体类 表——>类 student
列——>字段
外键列 对象类型
接口 封装对表操作的方法(crud)
StudentDao
实现类
StudentDaoImpl
包:XXX.dao
工具类 BaseDao
接口 StudentDao GradeDao
XXX.dao.impl 实现类
XXX.entity 实体类