在实际开发中,我们经常需要连接数据库进行数据的增、删、改、查等操作。而oracle数据库是一种十分常用的数据库,今天我们就来介绍一种使用MVC框架连接oracle数据库的方法。
首先,我们需要在web.xml中配置数据库所需要的参数:
<context-param> <param-name>driverClassName</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:ORCL</param-value> </context-param> <context-param> <param-name>username</param-name> <param-value>username</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>password</param-value> </context-param>
接着,我们需要引入相关的jar包:
<dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc8</artifactId> <version>12.2.0.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.8</version> </dependency>
引入完成后,我们需要创建一个数据库连接池:
public class DruidUtil { private static DruidDataSource dataSource; static { Properties props = new Properties(); InputStream in = DruidUtil.class.getResourceAsStream("/jdbc.properties"); try { props.load(in); dataSource = new DruidDataSource(); dataSource.setUrl(props.getProperty("url")); dataSource.setDriverClassName(props.getProperty("driverClassName")); dataSource.setUsername(props.getProperty("username")); dataSource.setPassword(props.getProperty("password")); dataSource.setInitialSize(Integer.parseInt(props.getProperty("initialSize"))); dataSource.setMinIdle(Integer.parseInt(props.getProperty("minIdle"))); dataSource.setMaxActive(Integer.parseInt(props.getProperty("maxActive"))); dataSource.setMaxWait(Long.parseLong(props.getProperty("maxWait"))); } catch (Exception e) { throw new RuntimeException(e); } } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
在getConnection方法中,我们使用了读取配置文件的方式来获取数据库连接信息,然后使用DruidDataSource创建出连接池对象。
最后,我们需要创建数据库访问类:
public class UserDao { public static List<User> findAll() { List<User> userList = new ArrayList<>(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DruidUtil.getConnection(); String sql = "SELECT * FROM user"; preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { User user = new User(); user.setId(resultSet.getInt("id")); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return userList; } }
在findAll方法中,我们使用DruidUtil类获取数据库连接,然后创建PreparedStatement对象并执行SQL语句查询出数据。最后,我们将查询出的数据封装到User实体类中,并将其添加到userList中返回。
以上就是使用MVC框架连接oracle数据库的方法,它可以方便我们进行数据库操作,提高开发效率。