2015-06-23 72 views
2

我想從使用預準備語句的表中選擇數據。但它似乎是我得到的語法錯誤,我不能單獨解決。SQL語法中的MySQLSyntaxErrorException

try { 

     Class.forName("com.mysql.jdbc.Driver"); 
     String url = "jdbc:mysql://localhost:3306/mydb"; 
     String dbusername = "root"; 
     String dbpassword = ""; // Change it to your Password 

     // Setup the connection with the DB 
     connection = DriverManager.getConnection(url, dbusername, 
       dbpassword); 

     String query = "SELECT * FROM admin WHERE username = ? AND password = ?"; 

     try { 
      // connection.setAutoCommit(false); 
      selectUser = connection.prepareStatement(query); 
      selectUser.setString(1, username); 
      selectUser.setString(2, password); 
      // Execute preparedstatement 
      ResultSet rs = selectUser.executeQuery(query); 

      // Output user details and query 
      System.out.println("Your user name is " + username); 
      System.out.println("Your password is " + password); 
      System.out.println("Query: " + query); 

      boolean more = rs.next(); 

      // if user does not exist set the validity variable to true 
      if (!more) { 
       System.out 
         .println("Sorry, you are not a registered user! Please sign up first!"); 
       user.setValid(false); 
      } 

      // if user exists set the validity variable to true 
      else if (more) { 
       String name = rs.getString("name"); 

       System.out.println("Welcome " + name); 
       user.setName(name); 
       user.setValid(true); 
      } 


     } catch (Exception e) { 
      System.out.println("Prepared Statement Error! " + e); 
     } 
    } catch (Exception e) { 
     System.out.println("Log in failed: An exception has occured! " + e); 
    } finally { 
    } 
    if (connection != null) { 
     try { 
      connection.close(); 
     } catch (Exception e) { 
      System.out.println("Connection closing exception occured! "); 
     } 
     connection = null; 
    } 

    return user; 
} 

我得到以下錯誤。

Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password = ?' at line 1 

但是在代碼行中看不到任何錯誤。

回答

0

變化

ResultSet rs = selectUser.executeQuery(query); 

ResultSet rs = selectUser.executeQuery(); 

當你已經準備的聲明中connection.prepareStatement(query);那麼爲什麼要通過查詢再次在selectUser.executeQuery(query);

+0

謝謝!我不知道那件事。刪除查詢參數保存了我的一天。 – Isuru

0

你想做的事就是用這個method

ResultSet rs = selectUser.executeQuery(); 
0

您已經加載了這裏準備的語句裏面查詢,

selectUser = connection.prepareStatement(query); 

因此通過執行它,

ResultSet rs = selectUser.executeQuery(); 

又讀,

How does PreparedStatement.executeQuery work?

相關問題