英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论