项目搭建
6.编写实体类:
ORM映射:表-类映射
7.编写基础公共类:
1. 数据库配置文件driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms? useUnciode=true&characterEncoding=utf8 user=root password=123456
2. 编写数据库的公共类
package com.zang.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; private static String user; private static String password; //静态代码块,类加载的时候就初始化了 static { try { //通过类加载器读取对应的资源 InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(is); driver=properties.getProperty(driver); url=properties.getProperty(url); user=properties.getProperty(user); password=properties.getProperty(password); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } public static Connection getconn(){ Connection connection = null; try { connection = DriverManager.getConnection(url, user, password); } catch (Exception throwables) { throwables.printStackTrace(); } return connection; } //编写查询公共类 public static ResultSet execute(Connection connection ,String sql,Object[] params,ResultSet resultSet,PreparedStatement statement) throws SQLException { statement = connection.prepareStatement(sql); for (int i = 0; i <params.length; i++) { statement.setObject(i+1,params[i]); } resultSet = statement.executeQuery(); return resultSet; } //编写增删改公共方法 public static int execute(Connection connection ,String sql,Object[] params,PreparedStatement statement) throws SQLException { statement = connection.prepareStatement(sql); for (int i = 0; i <params.length; i++) { statement.setObject(i+1,params[i]); } int update = statement.executeUpdate(); return update; } //释放资源 public static boolean closeresourse(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){ boolean flag=true; if(resultSet!=null){ try { resultSet.close(); resultSet=null; } catch (SQLException throwables) { throwables.printStackTrace(); flag=false; } } if(preparedStatement!=null){ try { preparedStatement.close(); preparedStatement=null; } catch (SQLException throwables) { throwables.printStackTrace(); flag=false; } } if(connection!=null){ try { connection.close(); connection=null; } catch (SQLException throwables) { throwables.printStackTrace(); flag=false; } } return flag; } }
- 编写字符编码过滤器
- 导入静态代码