How to add pictures to mysql: First create a method to read pictures using FileInputStream; then connect to the database and write sql statements, and use PreparedStatement to execute sql statements.
The operating environment of this tutorial: Windows 7 system, mysql version 8.0.22. This method is suitable for all brands of computers.
Related free learning recommendations: mysql video tutorial
How to add pictures to mysql:
1. Effect
Isn’t it saving a string? You can look at the data type on the left.
2. Get blob data
We create a method to read the image using FileInputStream
, and ByteArrayOutputStream
will read Write the fetched data into the byte[] array, and then
public static byte[] getImgStr(String path) throws IOException { FileInputStream fis = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); int len = 0; byte[] b = new byte[1024]; while ((len = fis.read(b))!= -1){ out.write(b,0,len); } //接收out byte[] array = out.toByteArray(); fis.close(); out.close(); return array; }
3. Connect to the database and write the sql statement
Use Blob to create a Blob, and then add the data we obtained Convert the image data to blob type, and then use PreparedStatement to execute the sql statement, because it supports placeholders and has a setBlob method that can directly write the value in our blob address to the database. And then you're done.
public static void main(String[] args) { /* 加载驱动 */ try { Class.forName("com.mysql.cj.jdbc.Driver"); //获取连接 String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"; String user= "root"; String password ="123456"; try { Connection connection = DriverManager.getConnection(url,user,password); /* 插入图片 */ byte[] arr = getImgStr("图片地址"); Blob blob = connection.createBlob(); blob.setBytes(1,arr); String sql = "insert into pictures (name,pic,date) values('张三',?,'2015-01-01')"; PreparedStatement ps = connection.prepareStatement(sql); ps.setBlob(1,blob); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } }
Related free learning recommendations: php programming (video)
The above is the detailed content of How to add pictures to mysql. For more information, please follow other related articles on the PHP Chinese website!