将图片存到数据库中通常有两种方式:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ImageToDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
String imagePath = "path/to/image.jpg";
String imageName = "image.jpg";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
File imageFile = new File(imagePath);
byte[] imageData = new byte[(int) imageFile.length()];
try (FileInputStream fis = new FileInputStream(imageFile)) {
fis.read(imageData);
}
String sql = "INSERT INTO images (name, image_data) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, imageName);
pstmt.setBytes(2, imageData);
pstmt.executeUpdate();
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ImageUrlToDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
String imageUrl = "https://example.com/images/image.jpg";
String imageName = "image.jpg";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "INSERT INTO images (name, image_url) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, imageName);
pstmt.setString(2, imageUrl);
pstmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云