Java - 如何在SQLite中插入值?

时间:2016-06-08 22:55:45

标签: java sqlite insert syntax-error sqlexception

我从SQLite开始,我创建了我的数据库并且连接正常。 当我尝试插入一个值(db为空)时,我收到以下错误:

  

java.sql.SQLException:near“.684”:语法错误

WARNINGS:
?: (security.W001) You do not have 'django.middleware.security.SecurityMiddleware' in your MIDDLEWARE_CLASSES so the SECURE_HSTS_SECONDS, SECURE_CONTENT_TYPE_NOSNIFF, SECURE_BROWSER_XSS_FILTER, and SECURE_SSL_REDIRECT settings will have no effect.
?: (security.W009) Your SECRET_KEY has less than 50 characters or less than 5 unique characters. Please generate a long and random SECRET_KEY, otherwise many of Django's security-critical features will be vulnerable to attack.
?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE_CLASSES, but you have not set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.
?: (security.W017) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE_CLASSES, but you have not set CSRF_COOKIE_HTTPONLY to True. Using an HttpOnly CSRF cookie makes it more difficult for cross-site scripting attacks to steal the CSRF token.
?: (security.W018) You should not have DEBUG set to True in deployment.
?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your MIDDLEWARE_CLASSES, but X_FRAME_OPTIONS is not set to 'DENY'. The default is 'SAMEORIGIN', but unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to 'DENY'.
?: (security.W020) ALLOWED_HOSTS must not be empty in deployment.

System check identified 8 issues (0 silenced).

import java.sql.*;

public class connection{
    String route = "C:\\Freeman SA.db";
    Connection c = null;
    Statement stat = null;
    String op;

    public void connect(){
        try{
            c = DriverManager.getConnection("jdbc:sqlite:"+route);
            if (c!=null)
                System.out.println("Connected to db.");
        }
        catch (SQLException ex) {
            System.err.println("Couldn't connect."+ex.getMessage());
        }
    }

    public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{
        connect();
        try {
            stat = c.createStatement();
            op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");";
            stat.executeUpdate(op);       //Here is the problem
            stat.close();
        }
        catch (SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        c.close();
    }
}

PD:我在这里学习:http://www.tutorialspoint.com/sqlite/sqlite_java.htm

2 个答案:

答案 0 :(得分:2)

通过连接像这样的字符串来创建SQL语句是个坏主意。对SQL注入攻击和Little Bobby Tables进行一些研究。

PreparedStatement是一个更好的主意。验证后绑定变量。

看看这是否会让你的生活更美好:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Demo RenumerationDao
 * Created by Michael
 * Creation date 6/8/2016.
 * @link https://stackoverflow.com/questions/37714254/java-how-can-i-insert-values-in-sqlite/37714292#37714292
 */
public class RenumerationDao {

    private static final String INSERT_SQL = "INSERT INTO Remuneraciones(Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES(?, ?, ?, ?, ?, ?)";

    private Connection connection; // Better to get this from a pool.

    public RenumerationDao(Connection connection) {
        this.connection = connection;
    }

    public int insert(String firstName, String lastName, String id, int age, int timeInHours, int salary) {
        int numRowsInserted = 0;
        PreparedStatement ps = null;
        try {
            ps = this.connection.prepareStatement(INSERT_SQL);
            ps.setString(1, firstName);
            ps.setString(2, lastName);
            ps.setString(3, id);
            ps.setInt(4, timeInHours);
            ps.setInt(5, age);  // You'll have to update this each and every year. BirthDate would be better.
            ps.setInt(6, salary);
            numRowsInserted = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps);
        }
        return numRowsInserted;
    }

    public static void close(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:1)

我打印了String op并向我展示了这个:

INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (Charlie, White, 18.954.621-K, 21, 2, 650000);

我错过了String值中的引号,它应该是这样的:

INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES ('Charlie', 'White', '18.954.621-K', 21, 2, 650000);

修正了功能并正常工作

public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{
        connect();
        NAME = "'"+NAME+"'";
        LNAME = "'"+LNAME+"'";
        ID = "'"+ID+"'";
        try {
            stat = c.createStatement();
            op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");";
            stat.executeUpdate(op);       //Here is the problem
            stat.close();
        }
        catch (SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        c.close();
    }
}

感谢您的回复和读者。