2017-06-16 78 views
1

我想刪除其中有場與由我指定的值記錄記錄:刪除哪些字段指定值

public static void delete(String firstName, String lastName, int age) 
{ 
    try 
    { 
     Statement myStmt = connection.createStatement(); 
     String sql = "delete from students where firstName='" + firstName + "', lastName='" + lastName + "', age='" + age + "'"; 
     myStmt.executeUpdate(sql); 
    } 
    catch (SQLException e) 
    {e.printStackTrace();} 
} 

的代碼不能正常工作。我絕對相信它的問題。請幫助我做正確的sql。我如何在表格中找到哪些字段由我指定的值?

這裏是一個錯誤,我越來越:

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 'where firstName='deleted', lastName='deleted', age='10'' at line 1 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
    at java.lang.reflect.Constructor.newInstance(Unknown Source) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) 
    at com.mysql.jdbc.Util.getInstance(Util.java:408) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486) 
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) 
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) 
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) 
    at Driver.delete(Driver.java:76) 
    at Driver.main(Driver.java:18) 
+0

做記錄需要匹配所有的值或他們 – FMashiro

+0

任一個@ FMashiro,所有的價值。 – ohidano

回答

5

爲了避免所有你必須在使用PreparedStatement這個語法錯誤,甚至SQL注入,因此,你可以使用:

String query = "delete from students where firstName=? and lastName=? and age=?"; 
try (PreparedStatement delete = connection.prepareStatement(query)) { 

    delete.setString(1, firstName); 
    delete.setString(2, lastName); 
    delete.setInt(3, age);//<-----------(1) 

    delete.executeUpdate(); 
} 
  • (1)我不知道如果年齡爲int或varchar,所以如果年齡是一個字符串,你必須改用setString。

你真正的問題是,你必須使用andorwhere而不是,

where firstName='" + firstName + "', lastName='" + lastName + "', age='" + age + "'"; 
//----------------------------------^----------------------------^ 
3

你的SQL不正確,應該是:

String sql = "DELETE FROM students WHERE firstName='" + firstName + "' AND lastName='" + lastName + "' AND age='" + age + "'"; 

你可以在你WHERE子句只獨立的條件下使用的關鍵字,如ANDOR逗號在SQL查詢的該部分中是無效的分隔符。

+0

好的。等一下,我會試試看。 – ohidano

+4

並使用'PreparedStatement'來避免SQL注入攻擊。 –

+0

@AndrewS不過,我不知道Java足以提供準備好的語句的答案。如果你願意,你可以發表一個OP的例子 – FMashiro