一、DAO的介绍
一个JAVA项目包括表示层、业务层和持久化层(数据访问层)。
表示层用于和用户进行交互,业务层用于表示层和持久化层进行交互,持久化层用于和数据库交互。
这里我们的DAO(Data Access Objects:数据访问对象)就是完成持久化层的一些功能。
二、本文所用到的数据库
--建库
use master
go
if exists(select *from sysdatabases where name ='myDB' )
drop database myDB
go
create database myDB
go
--建表
use myDB
go
if exists(select * from sysobjects wherename='student')
drop table student
go
create table student(
stuId int not null,
stuName varchar(50) not null,
birsday date not null
)
go
insert into student(stuId,stuName,birsday)
values (1,'张三','1988-01-12')
insert into student (stuId,stuName,birsday)
values (2,'李斯','1989-04-10')
三、DAO编写步骤
一般建立四个包:dao包、db包、entity包、test包。
dao包中编写DAO类,如StudentDAO。
db包中编写Config常量接口,DbManager类用于加载驱动程序,创建连接等。
entity包中为实体类,一般一个表对应一个实体类。
test包中编写主函数和测试类。
1、在entity包中创建实体类
实体类的名称一般与表一致,这里为Student
需要包含Student中的所有属性,构造函数(一般为两个:不带参数的和带全部参数的)getset方法,重写toString和equals方法。
2、在db包中添加Config常量接口和DbManager类
Config中的常量一般为DRIVER、URL、DBNAME、UNAME、PWD等,方便以后想更改时直接在这里更改。
DbMagager是一个工具类,里面包含静态属性和静态方法。方法主要有:
public static int update(Stringsql)用来执行insert update delete语句。
public static ResultSet query(Stringsql) 用来执行select语句。
public static voidclose()用来关闭资源。
3、在dao包中添加DAO类(这里为Student)
用来对数据库和数据库数据进行操作。主要方法包括:
public boolean save(Studentstudent)
public boolean delete(int id)
public boolean update(Student student)
public void findAll()
public Student findById(int id)
方法体中主要是编写SQL语句,然后调用工具类DbManager中对应方法。如
public boolean save(Student student) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String birthday = dateFormat.format(student.getBirsday());
String sql = "insert into student" +
"(stuId,stuName,birsday)" +
"values " +
"('"+ student.getStuId() + "','" + student.getStuName() + "','" +birthday + "')";
return DBManager.update(sql) == 1;
}
4、在test包中编写测试类(这里为StudentTest)
publicclass StudentTest {
public static void main(String[] args) {
StudentTest test = new StudentTest();
test.testSave();
}
public void testSave() {
Datedate = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
date = dateFormat.parse("1912-12-12");
}catch (ParseException e) {
e.printStackTrace();
}
Student student = new Student(1,"三毛",date);
StudentDAOstudentDAO = new StudentDAO();
if (studentDAO.save(student)) {
System.out.println("添加数据成功");
} else {
System.out.println("添加数据失败");
}
}
}
四、源程序
entity包:
package com.entity;
import java.util.Date;
public class Student {
private int stuId;//学生学号
private StringstuName;//学生姓名
private Datebirsday;//学生出生日期
public Student() {
super();
}
public Student(int stuId, String stuName, Datebirsday) {
super();
this.stuId = stuId;
this.stuName = stuName;
this.birsday = birsday;
}
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Date getBirsday() {
return birsday;
}
public void setBirsday(Date birsday) {
this.birsday = birsday;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
returntrue;
if (obj == null)
returnfalse;
if (getClass() !=obj.getClass())
returnfalse;
Student other = (Student)obj;
if (birsday == null) {
if(other.birsday != null)
returnfalse;
} else if(!birsday.equals(other.birsday))
returnfalse;
if (stuId != other.stuId)
returnfalse;
if (stuName == null) {
if(other.stuName != null)
returnfalse;
} else if(!stuName.equals(other.stuName))
returnfalse;
return true;
}
@Override
public String toString() {
return "Student [stuId=" +stuId + ", stuName=" + stuName
+", birsday=" + birsday + "]";
}
}
db包:
packagecom.db;
public interface Config{
public static final String DRIVER ="com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final StringURL ="jdbc:sqlserver://127.0.0.1:1433;databaseName=";
public static final String DBNAME = "myDB";
public static final StringUNAME = "as";
public static final StringPWD ="";
}
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbManager {
public static Connection con = null;
public static Statement sta = null;
public static ResultSet rs = null;
public static int update(String sql) {
System.out.println(sql);
int row = 0;
try {
Class.forName(Config.DRIVER);
con =DriverManager.getConnection(Config.URL+Config.DBNAME, Config.UNAME,Config.PWD);
sta =con.createStatement();
row =sta.executeUpdate(sql);
System.out.println(1== row);
} catch (ClassNotFoundExceptione) {
System.out.println("驱动程序没有找到");
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
close();
}
return row;
}
public static ResultSet query(String sql){
try{
Class.forName(Config.DRIVER);
con =DriverManager.getConnection(Config.URL+Config.DBNAME, Config.UNAME,Config.PWD);
sta =con.createStatement();
rs= sta.executeQuery(sql);
} catch (C lassNotFoundExceptione) {
System.out.println("驱动程序没有找到");
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
}
return rs;
}
public static void close() {
try {
if (rs !=null) {
rs.close();
rs=null;
}
if (sta !=null) {
sta.close();
sta= null;
}
if (con !=null) {
con.close();
con= null;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
dao包:
package com.dao;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.fan.db.DBManager;
import com.fan.entity.Student;
public class StudentDAO {
public boolean save(Student student) {
DateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd");
String birthday =dateFormat.format(student.getBirsday());
String sql = "insert intostudent" +
"(stuId,stuName,birsday)" +
"values " +
"('"+ student.getStuId() + "','" + student.getStuName() + "','" +birthday + "')";
return DBManager.update(sql) ==1;
}
public boolean delete(int id) {
String sql = " delete fromstudent where stuId = " + id + "";
return DBManager.update(sql)==1;
}
public boolean update(int id) {
String sql = " update student "+
"set" +
"stuName= '张大嘴', " +
"birsday= '1990-10-21' " +
"where" +
"stuId= " + id + "";
return DBManager.update(sql) ==1;
}
public Student findbyID(int id) {
String sql = "select * fromstudent where stuId=" + id + "";
DBManager.rs =DBManager.query(sql);
Student student = newStudent();
int i = 1;
try {
while(DBManager.rs.next()) {
student.setStuId(DBManager.rs.getInt(i++));
student.setStuName(DBManager.rs.getString(i++));
student.setBirsday(DBManager.rs.getDate(i++));
}
} catch (SQLException e){
e.printStackTrace();
} finally {
DBManager.close();
}
return student;
}
}
test包:
package com.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fan.dao.StudentDAO;
import com.fan.entity.Student;
public class StudentTest {
public static void main(String[] args) {
StudentTest test = newStudentTest();
test.testSave();
test.testFindByID();
}
public void testSave(){
Date date = new Date();
DateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd");
try {
date =dateFormat.parse("1912-12-12");
} catch (ParseException e){
e.printStackTrace();
}
Student student = newStudent(1,"三毛",date);
StudentDAO studentDAO = newStudentDAO();
if (studentDAO.save(student)){
System.out.println("添加数据成功");
} else {
System.out.println("添加数据失败");
}
}
public voidtestFindByID(){
StudentDAO studentDAO = newStudentDAO();
Student student = newStudent();
student =studentDAO.findbyID(1);
System.out.println(student);
}
}