2016-07-17 46 views
0

有人請幫助我。我做的事情正確,但我得到一個error.It是一個JAVA應用程序鏈接到MYSQL wamp服務器。MySQLSyntaxErrorException在JAVA

錯誤: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL語法錯誤;檢查對應於你的MySQL服務器版本,在1號線附近使用「切格」正確的語法

我的代碼手冊:

public class MyQuery { 

    public Connection getConnection() { 
     Connection con = null; 
     try { 
      con = DriverManager.getConnection("jdbc:mysql://" 
        + "localhost:3306/employee_certificate", "root", ""); 
     } catch (SQLException ex) { 
      Logger.getLogger(Query.class.getName()) 
        .log(Level.SEVERE, null, ex); 
     } 
     return con; 
    } 

    public ArrayList<Item> getData(String EmpName) { 
     ArrayList<Item> list = new ArrayList<Item>(); 
     Connection con = getConnection(); 
     Statement st; 
     ResultSet rs; 
     try { 
      st = con.createStatement(); 
      rs = st.executeQuery("SELECT Emp_Id, Emp_Name, Department " 
        + "FROM staff WHERE Emp_Name = " + EmpName + " "); 
      Item I; 
      while (rs.next()) { 
       I = new Item(
         rs.getString("Emp_Id"), 
         rs.getString("Emp_Name"), 
         rs.getString("Department")); 
       list.add(I); 
      } 
     } catch (SQLException ex) { 
      Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     return list; 
    } 
} 
+2

將EmpName的值加引號,甚至更好的使用預處理語句 –

+0

報價沒有工作 –

+0

'WHERE Emp_Name ='「+ EmpName +」'「'請注意引號 –

回答

3

您的查詢字符串是不正確的。應該是這樣的:

rs=st.executeQuery("SELECT Emp_Id, Emp_Name, Department " 
      + "FROM staff WHERE Emp_Name = '"+EmpName+"'"); 

但我建議使用PreparedStatement對象發送SQL語句到數據庫。

String query = "SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?"; 
PreparedStatement preStatement = conn.prepareStatement(query); 
preStatement.setString(1, EmpName); 
ResultSet result = preStatement.executeQuery(); 

這種方法更安全,更方便。

1

您的查詢一個小問題:

​​

或安全查詢使用準備好的語句:

try { 
    PreparedStatement ps = connection.prepareStatement("SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?"); 
    ps.setString(1, EmpName); 
    rs = ps.executeUpdate(); 
    Item I; 
    while (rs.next()) { 
     I = new Item(rs.getString("Emp_Id"), rs.getString("Emp_Name"), rs.getString("Department")); 
     list.add(I); 
    } 
} catch (SQLException ex) { 
    Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex); 
} 
相關問題