在實際開發中,我們經常需要連接數據庫進行數據的增、刪、改、查等操作。而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數據庫的方法,它可以方便我們進行數據庫操作,提高開發效率。
下一篇php lb變量