MySQL存储图片使用JavaFX显示

在MySQL中,具有TinyBlob、Blob、MediumBlob、LongBlob四个用于存储二进制数据的数据类型

TypenMax(Byte)
TinyBlob255
Blob65K
MediumBlob16M
LongBlob4G

在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

欢迎讨论

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值