Exception in thread “main” java.sql.SQLException:

2020-04-16 05:03发布

I wrote a program that populates a database with a list of words. Problem is, it throws up the "Exception in thread "main" java.sql.SQLException: near "s": syntax error" every time I try to run the code. I realize similar questions have been asked on this forum, but in the context of MY code I am unable to rectify the error.

Thus I turn to you for help.

This is the code

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");
    }

}

and these are the errors I get when I run.

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)

标签: java sqlite
2条回答
在下西门庆
2楼-- · 2020-04-16 05:41

Use PreparedStatement to avoid problems with erroneous input:

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
查看更多
够拽才男人
3楼-- · 2020-04-16 06:05

Thanks Rogue for a good code. I had an error in SQLite during INSERT operation, SQL string contained "'" inside a text. So, an escaping in this way helped to me. I've changed a code a bit.

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();

So when I tried to insert a null value in INTEGER column, I used a method setObject().

查看更多
登录 后发表回答