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

时间:2011-04-25 02:37:57

标签: java 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();  
        }  
    }

}

2 个答案:

答案 0 :(得分:10)

你应该调用另一种方法。

首先要做的事情是:

错误代码(对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()?因为这是你麻烦的原因。

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

答案 1 :(得分:4)

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

相关问题