java - 线程 "main"java.sql.SQLException : near "s": syntax error 中的异常

标签 java sqlite

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

因此我向您寻求帮助。

这是代码

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)

最佳答案

使用PreparedStatement为了避免错误输入的问题:

PreparedStatement p = c.prepare("INSERT INTO WORDS (ID,CAT,WORD) VALUES(?, ?, ?)");
p.setInt(1, i);
p.setString(2, wordcat);
p.setString(3, word);
p.execute();
//commit results if using InnoDB, etc

关于java - 线程 "main"java.sql.SQLException : near "s": syntax error 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158386/

相关文章:

java - 有什么方法可以抑制 stringTemplate 中属性 a 未定义错误吗?

java - 输出图为数组中存储的每个整数显示一个星号。也许是starPrint?

iphone - 将字符串属性添加到 CoreDataBooks

javascript - 如何使用 jquery 和 javascript 显示数据库中的菜单项

android - Android 中简单的数据库访问方法

java - 如何访问Lucene索引中记录的关键字?

java - log4j 从哪里选择在哪个驱动器中保存日志

java - 我的列表仅在微调器中显示前两项

sqlite - 如何在cloud9 ide上查看或编辑sqlite db记录?

.net - 如何在 Visual Studio 2012 的 "Generate database wizard"中添加 SQLite 提供程序