我是noob 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();
//}
}
}
您的代碼可能很危險,您應該使用'setX'方法而不是添加字符串。至於你的問題,如果它在網絡上,我認爲它會變慢,你是否試圖ping機器以查看結果? – Djon
您是否使用連接池,或者每次需要時都創建新的連接?如果是後者,那麼做前者。和Djon +1。準備好的語句的要點是綁定參數以確保代碼安全。您的代碼容易受到SQL注入攻擊。 –
@Djon可能你建議OP使用'PreparedStatement'而不是簡單的'Statement',但這是代碼中的一個安全漏洞,它不會解決淨延遲問題。 –