2017-04-26 6 views
0

私はライブラリでsqlite-jdbc-3.16.1.jarとjava(eclipse)のsqliteデータベースを稼ぐ。データベースの最初の行を埋めるSQLインクリメントID

私は表1に5行があります:ID(ID整数PRIMARY KEY AUTOINCREMENT)、名前、ROW3、ROW4は、私は名前、ROW3とROW4、それ自体をインクリメントするIDを挿入したい

をROW5。

public static void insertTest(String name, byte[] contentRow3, byte[] contentRow4) { 

      String sql = "INSERT INTO table1(name, contentRow3, contentRow4) VALUES(?,?,?)"; 

      try (Connection conn = connect(); 
       PreparedStatement pstmt = conn.prepareStatement(sql)) { 
       pstmt.setString(2, name); 
       pstmt.setBytes(3, contentRow3); 
       pstmt.setBytes(4, contentRow4); 
       System.out.println("Added new Person to DB"); 
       pstmt.executeUpdate(); 
      } catch (SQLException e) { 
       System.out.println(e.getMessage()); 
      } 
     } 

エラー:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

ここでの問題は何ですか? Javaで

答えて

2

プレースホルダは、書類を作成し、私は、次の修正されたコードが動作する必要があることを期待指数1、ない2で始まる:

try (Connection conn = connect(); 
    PreparedStatement pstmt = conn.prepareStatement(sql)) { 
    pstmt.setString(1, name); 
    pstmt.setBytes(2, contentRow3); 
    pstmt.setBytes(3, contentRow4); 
    System.out.println("Added new Person to DB"); 
    pstmt.executeUpdate(); 
} catch (SQLException e) { 
    System.out.println(e.getMessage()); 
} 

あなたが取得している例外は、インデックス位置3が範囲外であることを訴えています。おそらく、あなたがpstmt.setBytes(3, contentRow4)を行ったときのフードの下で、第4の配列要素へのアクセスに変換されました。これは、配列インデックスがゼロベースであると仮定してインデックス3になります。

+0

setString後の数値が行番号ではないのですか? – nolags

+1

'PreparedStatement'で設定した値は、SQLクエリの疑問符プレースホルダに対応しています。インデックスは1から始まり、3つの疑問符があるので、1と2と3を設定する必要があります。 –

関連する問題