Dao模式(data Access Object 数据访问对象)
声明与实现分开
1.新建一个Dao接口,里面声明数据库访问规则。
package com.dao; /** * 定义操作数据库的方法 */ public interface User { /** * 查询所有 */ void insert(); }
2.新建一个Dao的实现类,具体实现早前定义的规则。
package com.dao.inpl; import com.dao.User; import java.sql.*; public class UserDaoImpl implements User { @Override public void insert() { Connection conn = null; Statement st = null; ResultSet rs = null; String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost:3306/user?&useSSL=false&serverTimezone=UTC"; String user = "root"; String pass = "123456"; try { //获取连接对象 Class.forName(JDBC_DRIVER); //打开一个连接 conn = DriverManager.getConnection(DB_URL, user, pass); //根据连接对象,得到Statement st = conn.createStatement(); //执行一个查询语句 String sql = "select * from tal_demo"; rs = st.executeQuery(sql); //从结果集中提取数据 while (rs.next()) { int Id = rs.getInt("id"); int age = rs.getInt("age"); String name = rs.getString("name"); System.out.println("Id:" + Id + ",名字:" + name + ",年龄:" + age); } } catch (Exception e) { e.printStackTrace(); } finally { //释放资源 try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } try { if (st != null) { st.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { st = null; } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { conn = null; } } } }
3.直接实现。
package com.test; import com.dao.User; import com.dao.inpl.UserDaoImpl; import org.junit.Test; public class TestUserDaoImpl { @Test /** * 测试接口 */ public void testFinal(){ User dao=new UserDaoImpl(); dao.insert(); } }
在项目中必须添加mysql-connector-java.jar包 不然会报错。
(:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver)