- public static void write(){
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- // 加载驱动
- Class.forName("com.mysql.jdbc.Driver");
- // 建立连接
- String url ="jdbc:mysql://localhost:3306/mydb2";
- String user ="root";
- String password = "123456";
- conn = DriverManager.getConnection(url, user, password);
- // 创建sql语句
- //String sql = "insert into test_blob(id,content) values(?,?)";
- String sql = "insert into test_blob(id,content) values(?,?)";
- pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, UUID.randomUUID().toString());
- // 类加载器加载资源
- URL uri = BlobTest.class.getClassLoader().getResource("cn/zengfansheng/blob/money.jpg");
- File file = new File(URLDecoder.decode(uri.getPath(), "utf-8"));
- InputStream is = new FileInputStream(file);
- pstmt.setBinaryStream(2, is, (int)file.length());
- // 执行sql语句
- int i = pstmt.executeUpdate();
- System.out.println(i>0?"数据写入数据库成功":"数据写入数据库失败");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } finally{
- // 关闭资源,从里到外
- try {
- if(pstmt!=null)
- pstmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- try {
- if(conn!=null)
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
复制代码 为什么会报这个错误,前面我存Clob时候代码也差不多,但是没有报错。- com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '????—??”????è????????é??é??Rè??U???[????—?é…??‰?.q???V??°8RMFè¤?????è?????p
- 7' at line 1
- at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
- at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
- at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
- at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
- at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
- at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
- at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
- at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
- at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
- at cn.zengfansheng.blob.BlobTest.write(BlobTest.java:50)
- at cn.zengfansheng.blob.BlobTest.main(BlobTest.java:20)
复制代码 |