简体   繁体   中英

InputMismatchException? I still can't figure it out

im trying to make an txt file into sqlite with java.

(ID,NAME,CATEGORY,XCOORDINATE,YCOORDINATE,LENGTH,WIDTH,FLOOR)

types are orderly INTEGER text text int int int int. (I create ID by AUTOINCREMENT.)

An example is like

 maleToilet room -58 0 58 48 9 femaleToilet room -58 -48 58 48 9 

here is the main code:

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

class Read{
public Scanner input;

public void openFile() {
    try {
        input = new Scanner(new File("D:\\room.txt"));
    } catch (FileNotFoundException fileNotFoundException) {
        System.err.println("Error opening file.");
        System.exit(1);
    }
}

public void closeFile() {
    if (input!=null) 
        input.close();
    }
}

public class TxtToSqlite
{
    public static void main( String args[] )
    {
        Read r = new Read();
        Connection c = null;
        Statement stmt = null;

    try {
  Class.forName("org.sqlite.JDBC");
  c = DriverManager.getConnection("jdbc:sqlite:test.db");
  c.setAutoCommit(false);

  stmt = c.createStatement();

  //create the schema 
  /*String sql = "CREATE TABLE ROOM " +
               "(ID INTEGER PRIMARY KEY AUTOINCREMENT," +
               " NAME           TEXT    NOT NULL, "+ 
               " CATEGORY       TEXT    NOT NULL, "+ 
               " XCOORDINATE    REAL    NOT NULL, "+ 
               " YCOORDINATE    REAL    NOT NULL, "+
               " LENGTH         REAL    NOT NULL, "+
               " WIDTH          REAL    NOT NULL, "+
               " FLOOR          INT     NOT NULL)";*/


  r.openFile();

  String sql = null;
  int i = 1;
  while(r.input.hasNext()){
    sql = "INSERT INTO ROOM (NAME,CATEGORY,XCOORDINATE,YCOORDINATE,LENGTH,WIDTH,FLOOR) " +
            "VALUES ("+"'"+r.input.next()+"', '"+r.input.next()+"', "+
            r.input.nextInt()+", "+r.input.nextInt()+", "+
            r.input.nextInt()+", "+r.input.nextInt()+", "+r.input.nextInt()+");";
    stmt.executeUpdate(sql);
    i++;
  }
  r.closeFile();


  stmt.close();
  c.close();
} catch (InputMismatchException e) {
    System.out.print("Input Error!");
} catch ( Exception e ) {
   System.err.println( e.getClass().getName() + ": " + e.getMessage() );
   System.exit(0);
}

} }

But it throws an InputMismatchException. So, can anyone help me with it? Thanks:)

BTW, I download sqlite-jdbc-3.7.2.jar from http://www.tutorialspoint.com/sqlite/sqlite_java.htm and make it into the referenced libraries.

As Smit says,

I correct the original one by changing the ID datatype to INTEGER and set it AUTOINCREMENT to make it easier.

then

Remove the c.setAutoCommit(false); in the main code to make it work.

Thank you all for answering! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM