将Blob转换为字符串只会在Java中返回Blob对象名称。

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

Converting Blob to String yields just the Blob object name in Java

问题

我正在尝试从MySQL数据库中读取一个包含随机文本的Blob。

我的代码如下:

Connection conn = DriverManager.getConnection(connection_string);
String message = "Some message";
byte[] messageBytes = message.getBytes("UTF-8");

Blob blob = conn.createBlob();
blob.setBytes(1l, messageBytes);

String sql = "INSERT INTO db.dbname('blob') VALUES ('" + blob + "');";
PreparedStatement pat = conn.prepareStatement(sql);
pat.executeUpdate();

在另一个类中,我有从数据库中读取blob字段的代码:

//一些用于读取blob字段的SQL代码
Blob readBlob = resultSet.getBlob("blob");
byte[] bytes = readBlob.getBytes(1, (int) readBlob.length());
String str = new String(bytes);

System.out.println(str);

输出结果为:com.mysql.cj.jdbc.Blob@3be81fc2

我的代码与StackOverflow上一些有效的解决方案完全相同,所以我不确定问题出在哪里。

英文:

I am trying to read a Blob from a MySQL db, containing some random text.

My code looks like this:

Connection conn = DriverManager.getConnection(connection_string);
String message = "Some message";
byte[] messageBytes = message.getBytes("UTF-8");

Blob blob = conn.createBlob();
blob.setBytes(1l,messageBytes);

String sql = "INSERT INTO db.dbname('blob') VALUES ('" + blob + "');"
PreparedStatement pat = conn.prepareStatement(sql);
pat.executeUpdate();

In another class I have the code to read the blob field from database:

//some SQL code to read the blob field here
Blob readBlob = resultSet.getBlob("blob");
byte[] bytes = readBlob.getBytes(1, (int) readBlob.length());
String str = new String(bytes);

System.out.println(str);

The output is: com.mysql.cj.jdbc.Blob@3be81fc2

My code is exactly the same as some of the working solutions on StackOverflow, so I don't know exactly what is wrong.

答案1

得分: 1

似乎在插入过程中出现了一个小错误。您的代码应该类似于:

String sql = "INSERT INTO db.dbname('blob') VALUES (?);"
PreparedStatement pat = conn.prepareStatement(sql);
pat.setBlob(1, blob);
pat.executeUpdate();

请使用带有占位符的预处理语句。否则,攻击者可能会轻易地发动SQL注入攻击。如果您想了解SQL注入的工作原理,YouTube上有一个很棒的Computerphile视频可以参考。

英文:

Seems like you make a small mistake during insertion. Your code should be something like:

String sql = "INSERT INTO db.dbname('blob') VALUES (?);"
PreparedStatement pat = conn.prepareStatement(sql);
pat.setBlob(1, blob);
pat.executeUpdate();

Please use prepared statements with those placeholders. Otherwise attackers could easily run an SQL injection attack. If you want to see how SQL injection works, there‘s a great Computerphile Video about it on YouTube.

huangapple
  • 本文由 发表于 2020年10月9日 01:59:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64268186.html
匿名

发表评论

匿名网友

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

确定