ArrayIndexOutOfBounds:尝试将图像作为BLOB添加到java中的sqlite数据库时为0
我正在尝试将图像作为blob插入sqlite数据库,但由于捕获到错误ArrayIndexOutOfBounds:尝试将图像作为BLOB添加到java中的sqlite数据库时为0,java,image,sqlite,connection,blob,Java,Image,Sqlite,Connection,Blob,我正在尝试将图像作为blob插入sqlite数据库,但由于捕获到错误java.lang.ArrayIndexOutOfBoundsException:0 我试着用一个try-catch语句来实现它,但我还是没弄明白。用于创建到数据库的连接的url是正确的,因为我一直通过其他方法使用相同的url,并且工作正常。任何帮助都将不胜感激 这是我的代码: public Boolean insertIntoProducts(String name, String description, String fi
java.lang.ArrayIndexOutOfBoundsException:0
我试着用一个try-catch语句来实现它,但我还是没弄明白。用于创建到数据库的连接的url
是正确的,因为我一直通过其他方法使用相同的url
,并且工作正常。任何帮助都将不胜感激
这是我的代码:
public Boolean insertIntoProducts(String name, String description, String filePath, Double price, int quantity) {
String url = "jdbc:sqlite:C:/Users/User/Desktop/MyDatabase.db";
Boolean success = false;
String sqlSelectID = "SELECT ID FROM Products ORDER BY ID DESC";
// Establishing a connection to the database
try {
// Initialising the image file
File image = new File(filePath);
FileInputStream fileInput = new FileInputStream(image);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int i; (i = fileInput.read(buf)) != -1;) {
// read all the bytes and store them in the array. Stores the binary data of the
// image
byteArray.write(buf, 0, i);
// Closing the file input to prevent memory leaks
fileInput.close();
try (Connection conn = DriverManager.getConnection(url)){
Statement statement = conn.();
ResultSet result = statement.executeQuery(sqlSelectID);
int id = 0;
if (result.next()) {
id = result.getInt("ID");
}
String sql = "INSERT INTO Products(ID,Name,Description,Quantity,Price,Image,isAuthorised) "
+ "VALUES (" + id + ",'" + name + "','" + description + "'," + quantity + ",'" + price
+ "','?','0');";
PreparedStatement pstatement = conn.prepareStatement(sql);
pstatement.setBytes(1, byteArray.toByteArray());
// Creating a variable to check if the insertion was successful depending if a
// row was added to the table
int row = 0;
row = pstatement.executeUpdate();
if (row > 0) {
success = true;
}
} catch (SQLException e) {
System.out.println(e);
}
}
} catch (Exception e) {
System.out.println(e);
}
return success;
}
错误出现在行
pstatement.setBytes(1,byteArray.toByteArray())中代码>
我已经检查了数组的长度,它的长度正确,但我不知道它试图访问什么以创建此错误省略捕获
es以便获得一个。错误来自哪一行?错误在pstatement.setBytes(1,byteArray.toByteArray())行中代码>