gpt4 book ai didi

java - 从 Tomcat DBCP JDBC 连接池获取连接对象

转载 作者:行者123 更新时间:2023-11-28 23:34:03 27 4
gpt4 key购买 nike

我有一个从 tomcat-dbcp 获得的 DataSource:

   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.Statement,com.mysql.jdbc.ResultSet,com.mysql.jdbc.PreparedStatementmysql 发出请求?

最佳答案

这里是一个使用查询参数并使用结果的选择查询的例子

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;
}

}

关于java - 从 Tomcat DBCP JDBC 连接池获取连接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com