它是否实现了连接池? 我相信PostgreSQL JDBC驱动程序是线程安全的,但我不确定在MYSQL上。Mysqldatasource线程安全
我想提出一个静态对象来处理这样的 包com.amzi.DataAccess DB连接;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class DBUtil {
private static MysqlDataSource dataSource = null;
public static MysqlDataSource getDataSource() {
if (dataSource == null) {
dataSource = new MysqlDataSource();
dataSource.setUser("root");
dataSource.setPassword(""); // Put your password here
dataSource.setUrl("jdbc:mysql://localhost:3306/user_device_table");
}
return dataSource;
}
}
而在另一个类我创建了一个连接,看是否有记录存在。 一旦我完成了连接,我就关闭它。
public boolean ValidateLogin(User user) {
boolean status = false;
PreparedStatement ps = null;
ResultSet rs = null;
Connection connection = null;
try {
connection = DBUtil.getDataSource().getConnection();
ps = connection.prepareStatement("select * from users where user_name=? and password=?");
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
rs = ps.executeQuery();
status = rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return status;
}
在大多数情况下(除非你使用旧版本的Tomcat),你应该使用你的应用程序服务器的配置设置数据源。这总是伴随着连接池配置。 –
@SteveC是必需的连接池吗?假设我在本地主机上运行3个不同的笔记本电脑,但它们都连接到同一个远程数据库?在这种情况下需要一个池吗? –
如果您需要扩展以便您可以拥有10个,100个或1000个用户,那么使用连接池将有很大帮助。 –