无法在SQLite数据库中插入数据

public static void main(String[] args) { try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\tim\\airline\\flightschedule.db"); PreparedStatement statement = connection.prepareStatement("INSERT INTO flights (flightID,departure,arrival)VALUES(?,?,?)"); statement.setInt(1,5); statement.setString(2,"David"); statement.setString(3,"Ortiz"); statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } } 

你应该调用另一种方法。

首先要做的事情是:

错误的代码(对SQL注入攻击很开放):

  statement = connection.createStatement(); resultSet = statement.executeQuery( "INSERT INTO flights ('flightID','departure','arrival') VALUES('"+flightID+"','"+departure+"','"+arrival+"')"); 

好代码:

  PreparedStatement statement = connection.prepareStatement( "INSERT INTO flights (flightID,departure,arrival) VALUES(?,?,?)"); statement.setString(1,flightID); statement.setString(2,departure); statement.setString(3,arrival); statement.executeUpdate(); // thanks to @lobster1234 for reminder! connection.commit(); 

您是否注意到我执行executeUpdate()而不是executeQuery()? 因为这是你麻烦的原因。

PS我还注意到你将flightID作为int传递给方法,但是将其作为字符串插入数据库。 通常不是一个好习惯。 坚持一种数据类型。 如果ID实际上是一个数字,请将其作为数据库中的数字,然后调用setInt(1,flightID); 或者,也将它作为String传递。

尝试在executeUpdate()之后调用connection.commit() executeUpdate() 。 您还可以获取executeUpdate()返回的值,并确保得到1而不是0,因为此调用返回受该语句影响的行数。