#題目 1(100分)請使用DBCP數據庫鏈接池改造上節課程做業中完成的輸出商品名稱和庫存的應用程序,經過鏈接池實現對數據庫的訪問。java
#回答 DBCP讀取數據庫內容mysql
package com.hava.datasource; import org.apache.commons.dbcp2.BasicDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Created by yanfa on 2016/9/24. */ public class DBPool { public static BasicDataSource basicDataSource = null; public final static String JDBC_DRIVER = "com.mysql.jdbc.Driver"; public final static String DB_URL = "jdbc:mysql://192.168.1.200/test"; public final static String USER = "root"; public final static String PASSWORD = "dVHJtG0T:pf*"; public void init() { basicDataSource = new BasicDataSource(); basicDataSource.setUrl(DB_URL); basicDataSource.setDriverClassName(JDBC_DRIVER); basicDataSource.setUsername(USER); basicDataSource.setPassword(PASSWORD); } public void test() { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = basicDataSource.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM product"); while(resultSet.next()) { Integer index = resultSet.getRow(); Integer Id = resultSet.getInt("Id"); String ProductName = resultSet.getString("ProductName"); Integer Inventory = resultSet.getInt("Inventory"); System.out.println("resultSet [row]:" + index + " [product.Id]:" + Id + " [product.ProductName]:" + ProductName + " [product.Inventory]:" + Inventory); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
測試與執行類sql
package com.hava.datasource; import junit.framework.TestCase; /** * Created by yanfa on 2016/9/26. */ public class DBPoolTest extends TestCase { public void testInit() throws Exception { } public void testTest1() throws Exception { DBPool dbPool = new DBPool(); dbPool.init(); dbPool.test(); } }
執行結果數據庫
resultSet [row]:1 [product.Id]:1 [product.ProductName]:bread [product.Inventory]:11 resultSet [row]:2 [product.Id]:2 [product.ProductName]:milk [product.Inventory]:8 Process finished with exit code 0