在上一阶段每次执行操作时,都需要建立连接,然后在关闭连接。这就产生了很多冗余的代码,这和我们应用的复用性是违背的。因此,我们需要创建一些简单工厂类来帮助我们提高代码的复用性。简单的说就是将重复的代码封装起来以便复用。
一、ConnectionFactory
1.1 ConnectionFactory的作用
利用工厂模式提高代码的重用性。
封装注册数据库的驱动和获得数据库的连接。
利用配置文件减少硬编码,便于维护。
1.2 配置文件jdbcinfo.properties
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=Student
jdbc.user=sa
jdbc.password=123
配置文件信息的获取
ConnectionFactory.class.getResourceAsStream("jdbcinfo.properties");//参数jdbcinfo.properties:指定了配置文件的路径,这里在一个目录下所以使用相对路径,
getResourceAsStream()方法返回的是一个输入流。
数据库连接Connection的获取
public static Connection getConnection();
首先在SQL Server数据库中创建一个Student表,表模型如下:
具体代码如下:
创建一个配置文件后缀名为.properties :jdbcinfo.properties
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=UserInfo jdbc.user=sa jdbc.password=123
简单工厂:ConnectionFactory.java
package com.mao.common; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; //简单工厂 public class ConnectionFactory { public static String DRIVER; public static String URL; public static String USER; public static String PASSWORD; static { Properties props=new Properties(); InputStream is=ConnectionFactory.class.getResourceAsStream("jdbcinfo.properties"); try { //从流中读取相应的配置文件信息将其加载到props中,将键值对封装进其中 props.load(is); //通过键获取相应的值 DRIVER=props.getProperty("jdbc.driver"); URL=props.getProperty("jdbc.url"); USER=props.getProperty("jdbc.user"); PASSWORD=props.getProperty("jdbc.password"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //获取数据库连接 public static Connection getConnection() { Connection conn=null; try { //加载驱动 Class.forName(DRIVER); //获取连接 conn=DriverManager.getConnection(URL, USER, PASSWORD); }catch(Exception e) { e.printStackTrace(); } return conn; } }
实体类:Student.java
package com.mao.common; import java.io.Serializable; //实体类 public class Student implements Serializable { private String id; private String name; private String sex; public Student() { } public Student(String id, String name, String sex) { super(); this.id = id; this.name = name; this.sex = sex; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
封装关闭连接的工具类:CloseDbUtils.java
package com.mao.common; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class CloseDbUtils { public static void closeConn(Connection conn,Statement state,ResultSet rs) { if(rs!=null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(state!=null) { try { state.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void closeConn(Connection conn,Statement state) { if(state!=null) { try { state.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void closeConn(Connection conn) { if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
封装具体操作的类:StudentJDBC.java
package com.mao.common; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class StudentJDBC { //插入一条记录 public static void insertItem(Student stu) { Connection conn=null; PreparedStatement state=null; try { conn=ConnectionFactory.getConnection(); //?表示占位符 String sql="INSERT INTO Student VALUES(?,?,?)"; state=conn.prepareStatement(sql); //表示第1个占位符的值为stu.getId() state.setString(1, stu.getId()); //表示第2个占位符的值为stu.getName() state.setString(2, stu.getName()); state.setString(3, stu.getSex()); int rows=state.executeUpdate(); System.out.println("成功插入:"+rows+"条记录"); }catch(Exception e) { try { //出现异常则事务回滚 conn.rollback(); } catch (SQLException e1) { } }finally { CloseDbUtils.closeConn(conn, state); } } public static void deleteItem(Student stu) { Connection conn=null; PreparedStatement state=null; try { conn=ConnectionFactory.getConnection(); String sql="DELETE FROM Student WHERE ID=?"; state=conn.prepareStatement(sql); state.setString(1, stu.getId()); int rows=state.executeUpdate(); System.out.println("成功删除:"+rows+"条记录"); }catch(Exception e) { }finally { CloseDbUtils.closeConn(conn, state); } } //修改数据 public static void updateItem(Student stu) { Connection conn=null; PreparedStatement state = null; try { conn=ConnectionFactory.getConnection(); String sql="UPDATE Student SET NAME=?,SEX=? WHERE ID=?"; state=conn.prepareStatement(sql); state.setString(1, stu.getName()); state.setString(2, stu.getSex()); state.setString(3, stu.getId()); int rows=state.executeUpdate(); System.out.println("成功更新:"+rows+"条记录"); }catch(Exception e) { e.printStackTrace(); }finally{ CloseDbUtils.closeConn(conn, state); } } //查询所有 public static void selectAll() { Connection conn=null; Statement state=null; ResultSet rs=null; try { conn=ConnectionFactory.getConnection(); state=conn.createStatement(); String sql="SELECT * FROM Student"; rs=state.executeQuery(sql); while(rs.next()) { System.out.println("ID:"+rs.getString("ID")+" NAME:"+rs.getString("NAME")+" SEX:"+rs.getString("SEX")); } state.executeQuery(sql); } catch (Exception e) { }finally { CloseDbUtils.closeConn(conn, state, rs); } } //查询单个记录 public static void selectItem(Student stu) { Connection conn=null; PreparedStatement state=null; ResultSet rs=null; try { conn=ConnectionFactory.getConnection(); String sql="SELECT NAME,SEX FROM Student WHERE ID=?"; state=conn.prepareStatement(sql); state.setString(1, stu.getId()); rs=state.executeQuery(); if(rs.next()) { System.out.println("NAME:"+rs.getString("NAME")+" SEX:"+rs.getString("SEX")); } }catch(Exception e) { e.printStackTrace(); }finally { CloseDbUtils.closeConn(conn, state, rs); } } }
测试类:MainActivity.java
import com.mao.common.ConnectionFactory; import com.mao.common.Student; import com.mao.common.StudentJDBC; public class MainActivity { public static void main(String[] args) { Student stu=new Student("4","mao4","男"); StudentJDBC stujdbc=new StudentJDBC(); stujdbc.insertItem(stu);//增 // stujdbc.deleteItem(stu);//删 // stujdbc.updateItem(stu);//更新数据 stujdbc.selectAll();//查所有记录 //stujdbc.selectItem(stu);//查单个记录 } }