从Tomcat DBCP JDBC连接池中获取Connection对象

时间:2014-11-01 02:12:03

标签: java mysql tomcat jdbc apache-commons-dbcp

我从DataSource获得了tomcat-dbcp

   import java.sql.Connection

   public Connection initPooledConnection()
{
    try {
        conn=(Connection)ds.getConnection();
        if(conn==null)
        {
            System.out.println("Failed to initialize the connection");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return conn;
}

如何继续使用com.mysql.jdbc.Statementcom.mysql.jdbc.ResultSetcom.mysql.jdbc.PreparedStatementmysql发出请求?

1 个答案:

答案 0 :(得分:0)

以下是使用查询参数并使用结果的选择查询的示例

import com.mysql.jdbc.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DataSource {
    public static Connection getConnection() {
        // Return a connection from the pool
    }
}

public class UserDAO {

    /**
     * Queries for User objects and returns them as a List
     */
    public List<User> getUsersForGroupID( int groupId ) {
        List<User> users = new ArrayList<User>();

        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // Check out a new connection from DataSource
            connection = DataSource.getConnection();

            // Define our query
            String query = "SELECT * FROM Users WHERE group_id = ?";

            // Create a PreparedStatement from the connection
            ps = connection.prepareStatement( query );

            // Add the parameter values (values for the ?s in the query)
            // The first one has an index of 1. They are not 0-based.
            ps.setInt( 1, groupId );

            // Execute the query and keep the returned ResultSet
            rs = ps.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setFullName(rs.getString("fullname"));
                users.add(user);
            }
        } catch (SQLException e) {
            // Log exception here
        } finally {
            try {
                if ( ps != null && !ps.isClosed() ) {
                    ps.close();
                }
            } catch (Exception e) {
                // Log exception thrown by ps.close()
            }
            try {
                if ( connection != null && !connection.isClosed() ) {
                    connection.close();
                }
            } catch (Exception e) {
                // Log exception thrown by connection.close();
            }
        }

        return users;
    }

}