有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

线程“main”java中的sqlite异常。sql。SQLException:接近“s”:语法错误

我写了一个程序,用单词列表填充数据库。问题是,每次我试图运行代码时,它都会抛出“线程中的异常”main“java.sql.SQLException:near“s”:syntax error”。我知道在这个论坛上也有人问过类似的问题,但在我的代码中,我无法纠正错误

因此我向你求助

这是密码

import java.io.*;
import java.sql.*;
import java.util.Scanner;

public class db_populate {

    public static void main(String[] args) throws SQLException, IOException,
            ClassNotFoundException {
        Connection c = null;
        Statement stmt = null;
        Scanner in = null;
        String word;
        String wordcat;
        String j, sql;
        int i = 0;

        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:dictionary.db");
        c.setAutoCommit(false);
        System.out.println("Opened database successfully");

        stmt = c.createStatement();

        in = new Scanner(new File("wordsEn.txt"));

        while (in.hasNext()) {
            word = in.nextLine();
            i++;
            j = Integer.toString(i);
            wordcat = word.substring(0, 2);
            sql = "INSERT INTO WORDS (ID,CAT,WORD) " + "VALUES(" + j + ",'"
                    + wordcat + "','" + word + "');";
            stmt.executeUpdate(sql);
        }

        stmt.close();
        c.commit();
        c.close();
        in.close();
        System.out.println("Records created successfully");
    }

}

这些是我跑步时遇到的错误

Opened database successfully
Exception in thread "main" java.sql.SQLException: near "s": syntax error
    at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
    at org.sqlite.core.NativeDB._exec(Native Method)
    at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
    at db_populate.main(db_populate.java:34)

共 (1) 个答案

  1. # 1 楼答案

    感谢Rogue提供的好代码。在插入操作期间,我在SQLite中出错,SQL字符串在文本中包含“'”。所以,以这种方式逃跑对我有帮助。 我对代码做了一些修改

    PreparedStatement prst = conn.prepareStatement(
        "INSERT INTO test(id, name, type) "
        + "VALUES(?, ?, ?)");
    prst.setLong(1, id);
    prst.setString(2, title);
    prst.setObject(3, type);
    prst.execute();
    

    所以,当我试图在INTEGER列中插入空值时,我使用了一个方法setObject()