- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
首先,我在线程安全编程方面经验不多。
我有一个MySQL类,我想在多个线程中使用一个实例来防止主线程中的代码阻塞。我阅读了有关连接池的信息,但我希望它尽可能简单。
这是我的 MySQL 类:
package com.vanillage.bukkitutils.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySQL {
private final String host;
private final int port;
private final String database;
private final String user;
private final String password;
private Connection connection;
public MySQL(String host, int port, String database, String user, String password) {
if (host == null) {
//TODO
}
if (database == null) {
//TODO
}
if (user == null) {
//TODO
}
if (password == null) {
//TODO
}
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getDatabase() {
return database;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public Connection getConnection() {
return connection;
}
public synchronized void connect() throws SQLException {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
}
public synchronized void checkConnection(int timeout) throws SQLException {
if (connection == null) {
connect();
} else {
boolean connectionValid = false;
try {
connectionValid = connection.isValid(timeout);
} catch (SQLException e) {
e.printStackTrace();
connect();
connectionValid = true;
}
if (!connectionValid) {
connect();
}
}
}
public synchronized ResultSet query(String query) throws SQLException {
return connection.prepareStatement(query).executeQuery();
}
public synchronized boolean update(String query) throws SQLException {
return connection.prepareStatement(query).execute();
}
public synchronized void close() throws SQLException {
if (connection != null) {
connection.close();
connection = null;
}
}
public synchronized boolean hasConnection(boolean checkOpen, boolean checkValid, int timeout) throws SQLException {
return connection != null && (!checkOpen || !connection.isClosed()) && (!checkValid || connection.isValid(timeout));
}
@Override
public String toString() {
return host + ":" + port + ", " + database + ", " + user + ", " + password;
}
}
是否可以使用 synchronized 关键字使我的 MySQL 类线程安全,因为我已经在上面的代码中使用了它?
我在不同线程中使用此类:
try {
mySQL.checkConnection(0);
try {
ResultSet resultSet = mySQL.query("SELECT * FROM Example");
if (resultSet.next()) {
System.out.println(resultSet.getString("Example"));
}
} catch (SQLException e) {
System.out.println("Error while executing query: " + e.getMessage());
}
} catch (SQLException e) {
System.out.println("Could not create a valid connection: " + e.getMessage());
}
我的问题:它是线程安全的吗?
编辑:
package testprogramm;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class TestProgramm {
private static final Scanner scanner = new Scanner(System.in);
private static Map<String, ComboPooledDataSource> dataSources = new HashMap<>();
public static void main(String[] args) {
//setup connections
ComboPooledDataSource testDataSource = new ComboPooledDataSource();
try {
testDataSource.setDriverClass("com.mysql.jdbc.Driver");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
testDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/database");
testDataSource.setUser("user");
testDataSource.setPassword("password");
dataSources.put("test", testDataSource);
while (true) {
String line = scanner.nextLine();
ComboPooledDataSource dataSource = dataSources.get(line);
if (dataSource != null) {
new Thread(new Runnable() {
ComboPooledDataSource dataSource = null;
public Runnable init(ComboPooledDataSource dataSource) {
this.dataSource = dataSource;
return this;
}
@Override
public void run() {
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM Example");
ResultSet resultSet = preparedStatement.executeQuery();
int i = 0;
while (resultSet.next()) {
i ++;
}
resultSet.close();//TODO: move to finally clause with null check and try/catch
preparedStatement.close();
connection.close();
System.out.println(i + " entries");
} catch (SQLException e) {
System.out.println("Error while executing statement: " + e.getMessage());
}
}
}.init(dataSource)).start();
} else {
System.out.println("No such connection");
}
}
}
}
最佳答案
您的问题:它是线程安全的吗?
我的回答:不,不是。
打破它的最简单方法:让您的线程之一调用 mySQL.getConnection().close();
除此之外:大多数连接根本不喜欢并行语句。那应该是什么交易范围呢?
您应该认真地考虑使用连接池。我最喜欢的选择是 c3p0。参见 http://www.mchange.com/projects/c3p0/#quickstart一个快速入门的例子。
确保安全
您无需传递 MySQL
实例,而是创建并配置 ComboPooledDataSource
(或您要使用的任何其他数据源)。然后在您的类中,从该池中获取一个 Connection
,执行您的 SQL 语句,然后关闭它。最方便的方法是使用 Java 7 引入的 try-with-resource:
try(Connection con = pool.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM whatever");
ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
//handle resultset
}
}
关于您现有类(class)的更多信息
如果你这样做,你将无法清理大量的 Statements
public synchronized ResultSet query(String query) throws SQLException {
//Statement never closed
return connection.prepareStatement(query).executeQuery();
}
public synchronized boolean update(String query) throws SQLException {
//Statement never closed
return connection.prepareStatement(query).execute();
}
关于Java 异步 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117164/
我有三张 table 。表 A 有选项名称(即颜色、尺寸)。表 B 有选项值名称(即蓝色、红色、黑色等)。表C通过将选项名称id和选项名称值id放在一起来建立关系。 我的查询需要显示值和选项的名称,而
在mysql中,如何计算一行中的非空单元格?我只想计算某些列之间的单元格,比如第 3-10 列之间的单元格。不是所有的列...同样,仅在该行中。 最佳答案 如果你想这样做,只能在 sql 中使用名称而
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 7 年前。 Improve this ques
我正在为版本7.6进行Elasticsearch查询 我的查询是这样的: { "query": { "bool": { "should": [ {
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 7 年前。 Improve this ques
是否可以编写一个查询来检查任一子查询(而不是一个子查询)是否正确? SELECT * FROM employees e WHERE NOT EXISTS (
我找到了很多关于我的问题的答案,但问题没有解决 我有表格,有数据,例如: Data 1 Data 2 Data 3
以下查询返回错误: 查询: SELECT Id, FirstName, LastName, OwnerId, PersonEmail FROM Account WHERE lower(PersonEm
以下查询返回错误: 查询: SELECT Id, FirstName, LastName, OwnerId, PersonEmail FROM Account WHERE lower(PersonEm
我从 EditText 中获取了 String 值。以及提交查询的按钮。 String sql=editQuery.getText().toString();// SELECT * FROM empl
我有一个或多或少有效的查询(关于结果),但处理大约需要 45 秒。这对于在 GUI 中呈现数据来说肯定太长了。 所以我的需求是找到一个更快/更高效的查询(几毫秒左右会很好)我的数据表大约有 3000
这是我第一次使用 Stack Overflow,所以我希望我以正确的方式提出这个问题。 我有 2 个 SQL 查询,我正在尝试比较和识别缺失值,尽管我无法将 NULL 字段添加到第二个查询中以识别缺失
什么是动态 SQL 查询?何时需要使用动态 SQL 查询?我使用的是 SQL Server 2005。 最佳答案 这里有几篇文章: Introduction to Dynamic SQL Dynami
include "mysql.php"; $query= "SELECT ID,name,displayname,established,summary,searchlink,im
我有一个查询要“转换”为 mysql。这是查询: select top 5 * from (select id, firstName, lastName, sum(fileSize) as To
通过我的研究,我发现至少从 EF 4.1 开始,EF 查询上的 .ToString() 方法将返回要运行的 SQL。事实上,这对我来说非常有用,使用 Entity Framework 5 和 6。 但
我在构造查询来执行以下操作时遇到问题: 按activity_type_id过滤联系人,仅显示最近事件具有所需activity_type_id或为NULL(无事件)的联系人 表格结构如下: 一个联系人可
如何让我输入数据库的信息在输入数据 5 分钟后自行更新? 假设我有一张 table : +--+--+-----+ |id|ip|count| +--+--+-----+ |
我正在尝试搜索正好是 4 位数字的 ID,我知道我需要使用 LENGTH() 字符串函数,但找不到如何使用它的示例。我正在尝试以下(和其他变体)但它们不起作用。 SELECT max(car_id)
我有一个在 mysql 上运行良好的 sql 查询(查询 + 连接): select sum(pa.price) from user u , purchase pu , pack pa where (
我是一名优秀的程序员,十分优秀!