Java向MySQL添加图片

public void insertHeadIcon() {
//图片地址
String path = “D:\Workspace\project\icon\100.jpg”;
File file = new File(path);
FileInputStream in = null;
Connection conn = null;
PreparedStatement pstat = null;
try {
//将file转为输入流
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
conn = DButils.getConnection();
String sql = “insert into userinfo (id,name,pass,state,icon,flag)values(?,?,?,?,?,?)”;
pstat = conn.prepareStatement(sql);
pstat.setInt(1, 1);
pstat.setString(2, “张三”);
pstat.setString(3, “123”);
pstat.setInt(4, “普通用户”);
pstat.setBinaryStream(5, in, in.available());
pstat.setInt(6, 1);
int i = pstat.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
DButils.close(null, pstat, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要将图片保存在数据库中,可以通过以下代码将图片转换为二进制数据并保存到数据库中: ```java String filePath = "path/to/image.jpg"; File imageFile = new File(filePath); FileInputStream fis = new FileInputStream(imageFile); byte[] imageData = new byte[(int) imageFile.length()]; fis.read(imageData); fis.close(); String url = "jdbc:mysql://localhost:3306/database_name"; String user = "username"; String password = "password"; Connection conn = DriverManager.getConnection(url, user, password); String sql = "INSERT INTO image_table (image_data) VALUES (?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setBytes(1, imageData); ps.executeUpdate(); ``` 这里假设你已经创建了一个名为 `image_table` 的表,该表包含一个名为 `image_data` 的 BLOB 类型列。 接下来,你可以通过以下代码读取数据库中的图片数据并将其显示在界面上: ```java String url = "jdbc:mysql://localhost:3306/database_name"; String user = "username"; String password = "password"; Connection conn = DriverManager.getConnection(url, user, password); String sql = "SELECT image_data FROM image_table WHERE image_id = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, imageId); ResultSet rs = ps.executeQuery(); if (rs.next()) { byte[] imageData = rs.getBytes("image_data"); ImageIcon imageIcon = new ImageIcon(imageData); JLabel imageLabel = new JLabel(imageIcon); // 将 imageLabel 添加到界面中显示图片 } ``` 这里假设你已经从界面中获取了要显示的图片的 ID,然后将其传递给 SQL 语句中的 `image_id` 参数。通过 `ResultSet` 对象获取到图片数据后,可以将其转换为 `ImageIcon` 对象,然后将其显示在界面上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值