【Java】JDBC连接数据库,数据访问和DAO模式。
1.建立lib目录,把mysql-connector-java-8.0.19.jar插件(这个插件可以在网上自行下载)放进去之后,再右键添加为库。
2.在src的同级目录下建立文件database.properties
敲:driver=com.mysql.cj.jdbc.Driver //加载驱动
url=jdbc:mysql://localhost:3306/t155?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 //数据库路径
username=root //数据库密码
password=root //数据库密码
3.创建一个包BaseDao
敲:
package DAO; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class BaseDao { private static String driver; // 数据库驱动字符串 private static String url; // 连接URL字符串 private static String user; // 数据库用户名 private static String password; // 用户密码 Connection conn = null; // 数据连接对象 static{//静态代码块,在类加载的时候执行 init(); } /** * 初始化连接参数,从配置文件里获得 */ public static void init(){ Properties params=new Properties(); String configFile = "database.properties";//配置文件路径 //加载配置文件到输入流中 InputStream is = BaseDao.class.getClassLoader() .getResourceAsStream(configFile); try { //从输入流中读取属性列表 params.load(is); } catch (IOException e) { e.printStackTrace(); } //根据指定的获取对应的值 driver=params.getProperty("driver"); url=params.getProperty("url"); user=params.getProperty("username"); password=params.getProperty("password"); } /** * 获取数据库连接对象 */ public Connection getConnection() { try { if(conn==null || conn.isClosed()) { // 获取连接并捕获异常 try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); // 异常处理 } } } catch (SQLException e) { e.printStackTrace(); } return conn; // 返回连接对象 } /** * 关闭数据库连接 * @param conn 数据库连接 * @param stmt Statement对象 * @param rs 结果集 */ public void closeAll(Connection conn, Statement stmt, ResultSet rs) { // 若结果集对象不为空,则关闭 if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } // 若Statement对象不为空,则关闭 if (stmt != null) { try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } // 若数据库连接对象不为空,则关闭 if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 增、删、改的操作 * @param preparedSql 预编译的 SQL 语句 * @param param 参数的字符串数组 * @return 影响的行数 */ public int exceuteUpdate (String preparedSql, Object[] param) { PreparedStatement pstmt = null; int num = 0; conn = getConnection(); try { pstmt = conn.prepareStatement(preparedSql); if (param != null) { for (int i = 0; i < param.length; i++) { //为预编译sql设置参数 pstmt.setObject(i + 1, param[i]); } } num = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally{ closeAll(conn,pstmt,null); } return num; } }
1.创建DAO包定义接口
2.再在本包中创建一个子包建立一个类实现类继承BaseDao和实现接口
3.在实现方法增,删,改,查
4.创建实体信息包entity和类建立属性和get set方法
5.创建VO流程包和process流程类
6.创建Test包和类Test运行