时间:2021-07-01 10:21:17 帮助过:4人阅读
package com.mycompany.dao; import java.util.List; import com.mycompany.domain.Student; /** * 学生DAO接口 * @author Administrator * */ public interface StudentDao { /** * 查询所有学生 * @return 学生列表 */ public List<Student> query(); /** * 添加学生 * @param student */ public void save(Student student); }
package com.mycompany.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.mycompany.dao.StudentDao; import com.mycompany.domain.Student; import com.mycompany.util.JDBCUtil; public class StudentDaoImpl implements StudentDao { public List<Student> query() { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; List<Student> students = new ArrayList<Student>(); String sql = "select * from student"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ int sid = resultSet.getInt("sid"); String name = resultSet.getString("name"); Student student = new Student(sid,name); students.add(student); } } catch (Exception e) { e.printStackTrace(); } finally{ JDBCUtil.release(resultSet, preparedStatement, connection); } return students; } public void save(Student student) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; List<Student> students = new ArrayList<Student>(); String sql = "insert into student(name) values(?)"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ JDBCUtil.release(resultSet, preparedStatement, connection); } } }
jdbc.url=jdbc:mysql:///test jdbc.user=root jdbc.password= jdbc.driverClass=com.mysql.jdbc.Driver
package com.mycompany.dao.impl; import java.util.List; import org.junit.Test; import com.mycompany.dao.StudentDao; import com.mycompany.domain.Student; public class StudentDaoImplTest { @Test public void testQuery(){ StudentDao studentDao = new StudentDaoImpl(); List<Student> students = studentDao.query(); for (Student student : students) { System.out.println(student); } } @Test public void testSave(){ Student student = new Student("test save"); StudentDao studentDao = new StudentDaoImpl(); studentDao.save(student); } }
本文出自 “素颜” 博客,谢绝转载!
jdbc访问数据库
标签:jdbc访问数据库