使用预编译,解决拼接sql 语句的问题。
@Test public void preparedStatement() throws Exception{ String sql = "insert into student (name,age) values (?,?)"; Connection connection = JdbcUtil.getConn(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "张三"); preparedStatement.setInt(2, 24); preparedStatement.executeUpdate(); JdbcUtil.close(connection, preparedStatement, null); }
操作Student表示列如下:
数据库操作Util:
package util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /*** * 实现对JDBC 的封装 * @author mqy * */ public class JdbcUtil { private static Properties properties = new Properties(); //使用静态代码块实现 jdbcUtil的字节码被加载锦jvm中 并且只执行一次。避免每次使用都注册 static{ try { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); properties.load(inputStream); Class.forName(properties.getProperty("driverClassName")); } catch (Exception e) { e.printStackTrace(); } } private JdbcUtil() { } //提供外界访问 返回数据库的连接对象 public static Connection getConn(){ try { return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password")); } catch (Exception e) { e.printStackTrace(); } return null; } //关闭资源 查询方法关闭资源 JdbcUtil.close(conn,st,rs) //增删改 关闭资源JdbcUtil.close(conn,st,null) public static void close(Connection conn,Statement st,ResultSet rs){ try { if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); }finally { try { if (st != null) { st.close(); } } catch (Exception e2) { e2.printStackTrace(); }finally { try { if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } } } }
properties文件:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///jdbcdemo username=root password=root
Student实体:
package somain; public class Student { private String name; private Long id; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", id=" + id + ", age=" + age + "]"; } public Student() { super(); } public Student(String name, Integer age) { super(); this.name = name; this.age = age; } }
Dao:
package dao; import java.util.List; import somain.Student; /** * * * */ public interface IStudentDao { /*** * 保存学生对象 * @param stu */ void save(Student stu); /** * 删除指定ID 的学生信息 * @param id */ void delete(Long id); /*** * 更新指定的学生信息 * @param newStu */ void update(Student newStu); /*** * 查询指定id 的学生信息 * @param id * @return */ Student get(Long id); /*** * 查询所有学生的对象,如果没有返回空集 * @return */ List<Student> list();
DaoImp:
package impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import dao.IStudentDao; import somain.Student; import util.JdbcUtil; public class StudentImpl implements IStudentDao { @Override public void save(Student stu) { String sql = "insert into student (name,age) values (?,?)"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JdbcUtil.getConn(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, stu.getName()); preparedStatement.setInt(2, stu.getAge()); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.close(connection, preparedStatement, null); } // TODO Auto-generated method stub } @Override public void delete(Long id) { String sql = "delete * from student where id =?"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JdbcUtil.getConn(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(1, id); preparedStatement.executeUpdate(); JdbcUtil.close(null, preparedStatement, null); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.close(null, preparedStatement, null); } // TODO Auto-generated method stub } @Override public void update(Student newStu) { // TODO Auto-generated method stub String sql = "update student set name=? age= ? where id= ?"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JdbcUtil.getConn(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, newStu.getName()); preparedStatement.setInt(2, newStu.getAge()); preparedStatement.setLong(3, newStu.getId()); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.close(connection, preparedStatement, null); } } @Override public Student get(Long id) { String sql = "select * from Student where id = ?"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet set = null; try { connection = JdbcUtil.getConn(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(1, id); set = preparedStatement.executeQuery(); if (set.next()) { Student student = new Student(); student.setAge(set.getInt("age")); student.setName(set.getString("name")); student.setId(set.getLong("id")); return student; } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.close(connection, preparedStatement, set); } // TODO Auto-generated method stub return null; } @Override public List<Student> list() { String sql = "select * from student"; List<Student> list = new ArrayList<>(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection= JdbcUtil.getConn(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { Student student = new Student(); student.setAge(resultSet.getInt("age")); student.setName(resultSet.getString("name")); student.setId(resultSet.getLong("id")); list.add(student); } } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtil.close(connection, preparedStatement, resultSet); } return list; } }
Test:
package test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; import dao.IStudentDao; import impl.StudentImpl; import somain.Student; public class StudentDaoTest { private IStudentDao dao = new StudentImpl(); @Test public void testSave() { //fail("Not yet implemented"); Student stu = new Student(); stu.setAge(30); stu.setName("lili"); dao.save(stu); } @Test public void testUpdate(){ Student student = new Student("lili", 45); student.setId(8L); dao.update(student); } @Test public void testDelete(){ IStudentDao dao = new StudentImpl(); dao.delete(12L); } @Test public void testGet(){ Student student = dao.get(8L); System.out.println(student); } @Test public void testList(){ List list = new ArrayList<>(); list = dao.list(); System.out.println(list); } }