[英]Query latency client and server
我是菜鸟Java和MySQL用户。 这是我第一次编写用MySQL数据库实现的Java程序。 我有一个问题,为什么当我在位于不同计算机但位于同一局域网中的客户端中执行查询时,为什么会有这么长的延迟?
我的程序结构:
它是餐厅POS应用程序。 我的数据库和POS程序位于不同的计算机上。 我的查询命令全部构建在程序内部。 我的数据库只有一个模式和几个表。 这些表中存储的行数据很少。
问题:
当我在程序中按下按钮并运行查询并从数据库中选择一行时,tt至少花费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();
//}
}
}
通过网络建立连接非常昂贵,连接越远,连接越昂贵。
相反,我建议保留您的连接或使用连接池。 这意味着与创建新连接相比,您花费更多的时间来执行查询,插入或更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.