0

I want to add an image to the database.But nothing happens.There is a connection to the database.

     AssetManager assManager = getApplicationContext().getAssets();
      AssetFileDescriptor assetFileDescriptor = assManager.openFd("k.jpeg");
      FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();



      String newPath = path.toString();

        Bitmap bitmap = BitmapFactory.decodeStream(ims);

        imageView.setImageBitmap(bitmap);

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
      byte[] bytesImage = byteArrayOutputStream.toByteArray();

      String encodedImage = Base64.encodeToString(bytesImage, Base64.DEFAULT);
      PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO photo(id) VALUES (?)");
      FileInputStream  fin = new FileInputStream(fileDescriptor);
                preparedStatement.setBinaryStream(1, fin);

      //Executing the statement
      preparedStatement.executeUpdate()

writes an error com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect string value: '\xC5\x01\xB4\xBF\x0D\x00...' for column 'id' at row

16
  • Prefer preparedStatement.executeUpdate(); and then close preparedStatement Commented Sep 28, 2022 at 16:38
  • so I also tried it, it doesn’t work anyway, the image is not added Commented Sep 28, 2022 at 16:52
  • Did you close the connection? Is auto commit true? Commented Sep 28, 2022 at 19:07
  • yes my problem is com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect string value: '\xE8\x1A\x11\xBE\x0D\x00...' for column 'id' at row 1 Commented Sep 28, 2022 at 19:08
  • Hang on a minute, your query shows that you're attempting to set the ID column value. That is not the imsge itself Commented Sep 28, 2022 at 19:47

1 Answer 1

2

maybe you forget to set connection.

if your connection that's real have not been made.

You can connect to a database using the getConnection() method of the DriverManager class.

Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password")

semoga code ini bisa membantu anda

Sign up to request clarification or add additional context in comments.

2 Comments

I connected to the database but I can't add an image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.