在 SQLite 数据库中插入数据时遇到问题 [英] Trouble inserting data in a SQLite databae

查看:54
本文介绍了在 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();  
        }  
    }

}

推荐答案

你应该调用不同的方法.

You should call a different method.

首先要做的是:

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

Bad code (wide open to SQL Injection attack):

        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()?因为这是你麻烦的原因.

Have you noticed I do executeUpdate() instead of executeQuery()? Because this is the cause of your trouble.

附言我还注意到您将 flightID 作为 int 传递到方法中,但将其作为字符串插入到数据库中.通常不是一个好习惯.坚持一种数据类型.如果 ID 确实是一个数字,则在数据库中将其设为一个数字,然后调用 setInt(1,flightID);或者,也将其作为字符串传递.

P.S. I also noticed that you pass flightID into the method as int, but insert it into database as a string. Not a good practice usually. Stick to one datatype. If ID is really a number, make it a number in the database and then call setInt(1,flightID); alternatively, pass it around as String too.

这篇关于在 SQLite 数据库中插入数据时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆