数据库开发 - 数据库链接池单元做业

#题目 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
相关文章
相关标签/搜索