我是一个noob java和MySQL用户。这是我第一次编写用MySQL数据库实现的java程序。我有一个问题,当我在位于不同计算机但位于同一本地网络的客户端中执行查询时,为什么它会有如此多的延迟。
我的计划结构:
这是一家餐厅POS应用程序。我的DB和我的POS程序位于不同的计算机上。我的查询命令都是在我的程序中构建的。我的数据库只有一个模式和几个表。这些表中只存储了几行数据。
问题:
当我在我的程序中按下一个按钮并运行查询并从我的数据库中选择一行时,至少需要1秒来执行它并返回一些东西。所以我尝试将我的程序移动到与数据库服务器相同的计算机上。它比以前快10倍。我的天啊。到底是怎么回事。 我不知道为什么在查询通过本地网络运行时需要这么长时间。有人可以解释我为什么以及什么是使其实时的替代方法,如果可能的话。
我的示例查询代码:
Connection co = null;
PreparedStatement ps= null;
try{
co = myconnection.getConnection();
String insert = "INSERT INTO `R`.`order` (name, firstCourse, secondCourse, thirdCourse, seafood, other, dessert, drink, price, quantity, note, type, position , time_in ,subtable, tid , aid ) ";
insert += "VALUE ( '"+itemName+"','"+itemFirst+"','"+itemSecond+"','"+itemThird+"','"+itemSeafood+"','"+itemOther+"','"+itemDessert+"','"+itemDrink+"','"+itemPrice+"','"+num+"','"+notes+"','"+type+"','"+position+"','"+dateTime+"','"+subcheck+"','"+tableID+"','"+userID+"')";
ps = co.prepareStatement(insert);
ps.executeUpdate();
this.updateJTable();
}catch(Exception e){
System.out.println("error occur when insert item:"+e);
}finally{
try {
ps.close();
co.close();
} catch (SQLException e) { /* ignored */}
}
这是我的连接类:
import java.sql.*;
public class myConnection {
public static Connection getConnection() throws Exception {
String url = "jdbc:mysql://192.168.1.2:3306/r";
String user = "root";
String pass = "";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
try{
connection = DriverManager.getConnection(url, user, pass);
}catch (SQLException ex) {
ex.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection connection) throws SQLException {
//if (connection != null && !connection.isClosed()) {
connection.close();
//}
}
public void closeRs(ResultSet resultSet) throws SQLException{
//if (resultSet != null) {
resultSet.close();
//}
}
public void closePs(PreparedStatement preparedStatement) throws SQLException{
//if (preparedStatement != null) {
preparedStatement.close();
//}
}
}
答案 0 :(得分:5)
通过网络建立连接非常昂贵,连接越多,它就越昂贵。
相反,我建议您保持连接或使用连接池。这意味着您花费更多时间执行查询或插入或更新,而不是创建新连接。