Java-尝试对SQLite使用.setBytes函数,但获取ArrayIndexOutOfBounds 0错误
我试图将图像作为blob插入数据库,首先我将图像创建为ByteArrayOutsream,然后在我准备的语句中将其作为参数使用,但是,我得到了Java-尝试对SQLite使用.setBytes函数,但获取ArrayIndexOutOfBounds 0错误,java,sqlite,jdbc,blob,Java,Sqlite,Jdbc,Blob,我试图将图像作为blob插入数据库,首先我将图像创建为ByteArrayOutsream,然后在我准备的语句中将其作为参数使用,但是,我得到了java.lang.ArrayIndexOutOfBoundsException:0错误,并且我已经检查了数组长度和值是否都正确,因此我不知道数组中的哪个位置正试图访问以产生此错误 这是我的密码: public Boolean insertIntoProducts(String name, String description, String filePa
java.lang.ArrayIndexOutOfBoundsException:0
错误,并且我已经检查了数组长度和值是否都正确,因此我不知道数组中的哪个位置正试图访问以产生此错误
这是我的密码:
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";
filePath = filePath.replace("\\", "/");
// Establishing a connection to the database
String sql = "INSERT INTO Products(ID,Name,Description,Quantity,Price,Image,isAuthorised) "
+ "VALUES (" + quantity + ",'" + name + "','" + description + "'," + quantity + ",'" + price
+ "','?','0');";
try (Connection conn = DriverManager.getConnection(url)) {
PreparedStatement pstatement = conn.prepareStatement(sql);
File image = new File(filePath);
FileInputStream input = new FileInputStream(image);
ByteArrayOutputStream barray = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for(int readNum; (readNum = input.read(buffer)) != -1;) {
barray.write(buffer, 0 , readNum);
}
input.close();
int i = barray.toByteArray().length;
byte[] array = new byte[i];
array = barray.toByteArray();
pstatement.setBytes(1, array);
pstatement.executeUpdate();
success = true;
}catch(Exception e) {
System.out.println(e.getCause());
}
return success;
}
我在第
pstatement.setBytes(1,数组)行得到错误代码>请发布完整的异常堆栈跟踪。您的问题似乎来自于使用问号的文本?
,您需要使用表示参数的?
(不是引号)。您似乎知道如何使用准备好的语句,那么为什么还要将值连接到查询字符串中呢?这是不安全的。对所有动态值使用参数。@MarkRotterVeel非常感谢您,它可以工作!!!好的,谢谢你对这些参数的评论,我将为所有参数使用.set函数。再次感谢你@从技术上讲,这似乎是一个bug,因为驱动程序不应该抛出ArrayIndexOutOfBoundsException
,但是改为SQLException
。@markrotVeel是的,我也想知道为什么错误是ArrayIndexOutOfBoundsException
在parameterindex 1没有任何设置