I am making a Object Detection app which uses YOLOv8 for Detection and Java for the GUI. This is being made as a college project and I was just told that I need to add a database into it but due to not much experience in Back-end I can’t successfully do that.
I have tried using ClaudeAI for the code of it because I don’t have much time left for submitting it.
What I want the database to do is store the previously tested images and display them whenever the user logs in.
I tried this code which I got from Claude AI.
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.imageio.ImageIO;
public class ImageStore {
public static void main(String[] args) {
String imagePath = "output/annotated_image.jpg";
String dbUrl = "jdbc:mysql://localhost:3306/image";
String dbUser = "root";
String dbPassword = "your_password";
storeImageToDatabase(imagePath, dbUrl, dbUser, dbPassword);
}
public static void storeImageToDatabase(String imagePath, String dbUrl, String dbUser, String dbPassword) {
Connection connection = null;
PreparedStatement pstmt = null;
try {
// Read image from file
File imageFile = new File(imagePath);
BufferedImage bufferedImage = ImageIO.read(imageFile);
// Convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
byte[] imageBytes = baos.toByteArray();
// Establish database connection
connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
// Prepare SQL statement
String sql = "INSERT INTO images (name, image) VALUES (?, ?)";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, imageFile.getName());
pstmt.setBytes(2, imageBytes);
// Execute SQL statement
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new image was inserted successfully!");
}
} catch (IOException | SQLException ex) {
ex.printStackTrace();
} finally {
// Close resources
try {
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
I tried this as a sample to try out if it’s connecting or not. But it isn’t happening..
harshang patel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.