我正在尝试将图像作为blob插入到我的sqlite数据库中,但我无法让它工作,因为我正在捕获错误java.lang.ArrayIndexOutOfBoundsException: 0
我尝试用一个尝试捕获语句来做到这一点,但我又无法弄明白。用于创建与数据库的连接的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());
行
我已经检查了数组的长度并且它有正确的长度,但我不知道它正在尝试访问它以便创建此错误