在MySQL中,具有TinyBlob、Blob、MediumBlob、LongBlob四个用于存储二进制数据的数据类型
Typen | Max(Byte) |
---|---|
TinyBlob | 255 |
Blob | 65K |
MediumBlob | 16M |
LongBlob | 4G |
在JavaFX中,使用ImageView用于显示图片
效果如下:
JavaFX界面用于数据的写入
@FXML
private TableColumn<User, String> profile_picture;
initialize(){
profile_picture.setCellValueFactory(new PropertyValueFactory<User,String>("view"));
}
//触发事件
@FXML
void sub(ActionEvent event) throws ClassNotFoundException, SQLException, IOException {
//判断用户输入
//用正则表达式判断 t2 t4字符串能否转化为int
//判断文件是否存在
if(t2.getText().matches("\\d+") && t4.getText().matches("\\d+" ) && new File(t0.getText()).exists()){
//是否超出Blob类型的最大存储字节
if (new File(t0.getText()).length() > 60000){
alert("", "添加失败,输入不符要求","");
}
else{
//设置显示头像大小
ImageView v = new ImageView(new Image("file:\\"+t0.getText()));
v.setFitWidth(30);
v.setFitHeight(27);
User user = new User(t1.getText(),Integer.parseInt(t2.getText()),t3.getText(),Integer.parseInt(t4.getText()),v);
//添加数据显示到 ui界面
data.add(user);
//连接数据库
database.connect();
//添加的数据先入到数据库保存
database.insert(user,t0.getText());
//提示
alert("", "添加成功","");
}
}
else{
alert("", "添加失败,输入不符要求","");
}
数据持久层
public void insert(User p,String FilePath) throws SQLException, IOException {
String sql = "INSERT INTO game(name,credit,passward,match_times,picture) VALUES (?,?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,p.name);
preparedStatement.setInt(2,p.credit);
preparedStatement.setString(3,p.password);
preparedStatement.setInt(4,p.match_times);
//使用FileInputStream流写入数据库
FileInputStream fis = new FileInputStream(path);
preparedStatement.setBinaryStream(5,fis,fis.available());
//sql语句提交
preparedStatement.executeUpdate();
//资源关闭
fis.close();
preparedStatement.close();
}
github源码:
https://github.com/zslkdjaw/study_notes/tree/JDBC-write-files