2009-08-24 3 views
5

を使用してMySQLに[]バイトを挿入することはできません、私が使用しているコードです:は、次のJava

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 'key) VALUES ('test',_binary'?ʾ??s??u\'?}p?u')' at line 1 

私は、MySQL 5.0.41があります

byte[] bkey = key.getEncoded(); 
String query = "INSERT INTO keytable (name, key) VALUES (?,?)"; 
PreparedStatement pstmt = (PreparedStatement) connection.prepareStatement(query); 
pstmt.setString(1, "test"); 
pstmt.setBytes(2, bkey); 
pstmt.execute(); 

そして、次は私が得たエラーですJDBCライブラリとしてmysql-connector-java-5.1.7-bin.jar。 誰でも私をここで助けることができますか? ありがとうございます!

+2

'キー' である何のデータ型Iは、以下のコードを使用してこれを証明してきましたか? –

+0

テーブルに「説明」と入力して出力を表示できるので、扱う列の種類を知ることができますか? –

答えて

0

"setBytes()"ではなく "setBinaryStream()"を使用して、バイト配列に構築されたByteArrayInputStreamを渡してください。これはもちろん、列に割り当てられたデータ型がバイトを格納できることを前提としています... BLOB、BINARY、またはVARBINARYであることを確認してください。

また、バックティックを使用してオブジェクトを囲みます。 "key"はSQLキーワードですが、それ以外は良い習慣です:

String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)"; 
+0

も既に試しましたが、同じエラー –

+1

が別の提案で更新されました。 – Jonathan

-2

バイナリストリームを追加する必要があります。あなたはinputstreamにアクセスできますか?

FileInputStream input = new FileInputStream("myfile.gif"); 
String query = "INSERT INTO `keytable` (`name`, `key`) VALUES (?,?)"; 
PreparedStatement pstmt = (PreparedStatement) connection.prepareStatement(query); 
pstmt.setString(1, "test"); 
pstmt.setBinaryStream(2, input, input.available()); 
+0

'input.available()'は**を返しません**は長さを返します。 – BalusC

10

「キー」という列はSQLの予約語です。バックテックでそれを囲むと、物事はうまくいくはずです。さらに、列をSQL予約語ではない名前に変更することを検討してください。

MySQLのテーブル::

create table keytable (name varchar(255) not null, `key` blob not null); 

Javaコード:

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

public class MySQLBlobInsert { 

    public static void main(String[] args) { 
     try { 
      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
     Connection conn = null; 
     try { 
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); 
      byte[] bkey = "This is some binary stuff".getBytes(); 
      String query = "INSERT INTO keytable (name, `key`) VALUES (?,?)"; 
      PreparedStatement pstmt = conn.prepareStatement(query); 
      pstmt.setString(1, "test"); 
      pstmt.setBytes(2, bkey); 
      pstmt.execute(); 
     } catch (SQLException e) { 
      throw new RuntimeException(e); 
     } finally { 
      if (conn != null) { 
       try { conn.close(); } catch (SQLException e) {} 
      } 
     } 
     System.out.println("done :)"); 
    } 
} 
関連する問題