我目前正在尝试连接到不同的计算机,以便导入存储在每台计算机的本地数据库中的记录。到目前为止,我所看到的关于连接池的帖子是它为单个数据库创建了一个连接池。有没有办法使用线程创建到每台计算机的连接,以使任务更快?如果没有,那么连接和断开不同计算机的最有效方式是什么?
答案 0 :(得分:0)
你可以做这样的事情
public static void main(String... strings) {
//Pool of 5 threads
ExecutorService threadPool=Executors.newFixedThreadPool(5);
List<SQLServer> servers=new ArrayList<>();
SQLServer mySql1=new SQLServer();
mySql1.setUrl("jdbc://localhost:3306");
mySql1.setDatabase("testDb1");
mySql1.setUsername("admin");
mySql1.setPassword("root");
mySql1.setDriverClass("com.mysql.jdbc.Driver");
SQLServer mySql2=new SQLServer();
mySql2.setUrl("jdbc://localhost:3306");
mySql2.setDatabase("testDb2");
mySql2.setUsername("admin");
mySql2.setPassword("root");
mySql2.setDriverClass("com.mysql.jdbc.Driver");
//You can add as many as you want.
servers.add(mySql1);
servers.add(mySql2);
servers.forEach(s->{
SQLClient sqlClient=new SQLClient(s);
threadPool.execute(sqlClient);
});
}
class SQLClient implements Runnable {
private SQLServer sqlServer;
public SQLClient(SQLServer server) {
sqlServer = server;
}
@Override
public void run() {
try {
Class.forName(sqlServer.getDriverClass());
}
catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(sqlServer.getUrl()+"/"+sqlServer.getDatabase(),
sqlServer.getUsername(), sqlServer.getPassword());
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
try {
Statement statement=connection.createStatement();
statement.execute("your query");
// You can fetch you data here
}
catch (SQLException e) {
e.printStackTrace();
}
}
else {
System.out.println("Failed to make connection!");
}
}
}
class SQLServer {
String username;
String password;
String url;
String database;
String driverClass;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
}