InputMismatchException时?我还是想不出来

时间:2013-10-07 17:46:12

标签: java file sqlite exception inputmismatchexception

我试图用java创建一个txt文件到sqlite。

  

(ID,名称,类别,x坐标,y坐标,长度,宽度,FLOOR)

类型是有序的 INTEGER文本文本int int int int。 (我通过AUTOINCREMENT创建ID。)

一个例子就像

maleToilet    room -58   0 58 48 9 

femaleToilet  room -58 -48 58 48 9

这是主要代码:

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

} }

但它会抛出一个InputMismatchException。 那么,任何人都可以帮助我吗?感谢:)

顺便说一句,我从中下载了sqlite-jdbc-3.7.2.jar http://www.tutorialspoint.com/sqlite/sqlite_java.htm 并使其成为引用的库。

1 个答案:

答案 0 :(得分:1)

正如Smit所说,

  

我通过将 ID 数据类型更改为 INTEGER 来更正原始版本        并设置 AUTOINCREMENT 以使其更容易。

然后

  

删除主代码中的c.setAutoCommit(false); 以使其正常工作。

谢谢大家的回答! :)