我使用以下Java代码将图像插入MySQL数据库。
import org.jfree.chart.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
import java.sql.*;
import java.io.*;
import javax.swing.JFrame;
public class PieChart extends JFrame {
private static final long serialVersionUID = 1L;
public PieChart(String applicationTitle, String chartTitle) {
super(applicationTitle);
// This will create the dataset
PieDataset dataset = createDataset();
// based on the dataset we create the chart
JFreeChart chart = createChart(dataset, chartTitle);
// we put the chart into a panel
ByteArrayOutputStream out = new ByteArrayOutputStream();
ChartPanel chartPanel = new ChartPanel(chart);
// default size
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
// add it to our application
setContentPane(chartPanel);
try {
ChartUtilities.writeChartAsPNG(out, chart, 500, 270);
} catch (Exception e) {
}
try {
byte[] buf = out.toByteArray();
// setup stream for blob
ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
// get or create a connection here
// System.out.println("***********File Name **************" + filename);
//System.out.println("***********Employee ID ************" + emp_id);
System.out.println(inStream);
try {
String DB_URL = "jdbc:mysql://localhost/mydatabase";
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// Database credentials
String USER = "user";
String PASS = "pass";
// Get a connection to the database
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "insert into photos (id,photo) values (?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, "1");
ps.setBinaryStream(2, inStream, inStream.available());
int n = ps.executeUpdate();
inStream.close();
//Call delete function to delte the files which is uploaded
} catch (Exception e) {
System.out.println(e);
}
} catch (Exception exc) { // process error
System.out.println("process error" + exc);
}
}
/**
* Creates a sample dataset
*/
private PieDataset createDataset() {
DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Linux", 29);
result.setValue("Mac", 20);
result.setValue("Windows", 51);
return result;
}
/**
* Creates a chart
*/
private JFreeChart createChart(PieDataset dataset, String title) {
JFreeChart chart = ChartFactory.createPieChart3D(
title, // chart title
dataset, // data
true, // include legend
true,
false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
return chart;
}
}
由于某种原因未插入图像。正在插入ID但不插入图像。照片字段长71个字节,但不保留图像。 (类型为long blob
)。