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)
Use PreparedStatement to avoid problems with erroneous input:
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.
So when I tried to insert a null value in INTEGER column, I used a method setObject().