我正在尝试从不同的服务器访问数据库,但到目前为止没有成功。事件是,当我在组合框中选择“全部”时,该表将加载来自不同服务器的所有数据。
我仅连接到本地主机的当前代码工作正常。但是,当我尝试连接另一台服务器来加载它们的数据时,尝试将 192.168.1.51.sales.items
放入 String sqlall
时出现语法错误。另外,我尝试通过编写 cn.prepareStatement(sqlall) + cn1.prepareSatement("union Select * from 192.168.1.52.sales.items);
来修改 prepareStatement
我有不再了解如何连接两台服务器。
如果您发现我的代码有点困惑,我想事先道歉。谢谢。我的代码如下:
private void combobox_branchItemStateChanged(java.awt.event.ItemEvent evt) {
Object branch = combobox_branch.getSelectedItem();
try
{
// All is selected
if("All".equals(branch))
{
Connection cn = db.itemconnector.getConnection();
String sqlall = " Select * from sales2.items union Select * from sales1.items union Select * from sales.items " ; //I tried accessing multiple databases in my own localhost and worked.
PreparedStatement ps = cn.prepareStatement(sqlall);
ResultSet rs = ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
我在不同的包中有一个类,这是它的代码:
package db;
import java.sql.*;
public class itemconnector {
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
最佳答案
不可能在单个 SQL 查询中查询不同服务器上的不同数据库。
也不可能通过“连接”准备好的语句来解决这个问题。 (首先,这是毫无意义的 Java!)
您需要为每个单独的数据库服务器打开一个单独的连接
,并查询该服务器上的相关表。然后将来自单独 ResultSet
对象的信息组合到 Java 代码中。
“组合”就像迭代每个结果集中的结果并将它们添加到 Java 数据结构中......
关于java - 如何使用Java从特定服务器访问数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095646/