如何正确地将图像存储到SQL Server

huangapple go评论83阅读模式
英文:

How to properly store an image to SQL Server

问题

我已经使用以下代码将一些数据存储在SQL Server数据库中:

_bitmap = BitmapFactory.decodeFile(path);
byteArrayOutputStream = new ByteArrayOutputStream();
_bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
bytesImage = byteArrayOutputStream.toByteArray();
image = Base64.encodeToString(bytesImage, Base64.DEFAULT);

String query =
    "INSERT INTO EloanApp(SeqID,AppImage) VALUES ('" + seqid + "','" + image + "')";
Statement stmt = con.createStatement();
stmt.executeUpdate(query);

为了确保成功上传图像,我尝试导出存储在我的数据库中的图像并打开它。照片查看器显示**“看起来我们不支持这个文件格式。”**。这里可能出现了什么问题?

PS.

我使用以下方法导出了图像:

Simple Image Import and Export Using T-SQL for SQL Server

英文:

I have already stored some data in the SQL Server database with this code

_bitmap = BitmapFactory.decodeFile(path);
byteArrayOutputStream = new ByteArrayOutputStream();
_bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
bytesImage = byteArrayOutputStream.toByteArray();
image = Base64.encodeToString(bytesImage, Base64.DEFAULT);

String query =
    "INSERT INTO EloanApp(SeqID,AppImage) VALUES ('" + seqid + "','" + image + "')";
Statement stmt = con.createStatement();
stmt.executeUpdate(query);

And to make it sure that if it is successfully uploaded the image, I tried to export the image stored in my database and opened it, the photo viewer, shows "It looks like we don't support this file format." what seems could be the problem here?

PS.

I exported the image with this method

Simple Image Import and Export Using T-SQL for SQL Server

答案1

得分: 0

事实证明,移除这一行代码:

image = Base64.encodeToString(bytesImage, Base64.DEFAULT);

并且使用 PreparedStatement 来执行我的查询:

PreparedStatement preparedStatement = con.prepareStatement("INSERT INTO EloanApp(SeqID,AppImage) VALUES(?,?);

preparedStatement.setString(1, seq_id);
preparedStatement.setBytes(2, bytesImage);
preparedStatement.execute();

问题已解决!

英文:

It turned out that removing this line

image = Base64.encodeToString(bytesImage, Base64.DEFAULT);

and using a PreparedStatement to execute my query

PreparedStatement preparedStatement = con.prepareStatement("INSERT INTO EloanApp(SeqID,AppImage) VALUES(?,?);

preparedStatement.setString(1, seq_id);
preparedStatement.setBytes(2, bytesImage);
preparedStatement.execute();

solved the issue!

huangapple
  • 本文由 发表于 2023年8月10日 10:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定