如何使用jdbc从mysql中检索数组?

时间:2017-04-29 02:12:51

标签: java mysql arrays jdbc

public static void main(String[] args) {

    byte[] a1 = "stack".getBytes();  //**I need to insert this array a1 into mysql table and retrieve it** 

    for (byte b : a1) {
        System.out.println(b); //**just printing the array a1**
    }
    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", "admin");
        Statement stmt = conn.createStatement();
        String query = "INSERT INTO keytable (name, `key`) VALUES (?,?)";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "Nil");
        pstmt.setBytes(2, a1);  //**INSERTING a1**
        pstmt.execute();
        String sql = "SELECT 'key' FROM keytable";
        byte[] a2 = null;
        ResultSet rs = stmt.executeQuery(sql);
        rs.next();
        a2 = rs.getBytes(1); //copying the retrieved array into a2
        for (byte b : a2) {
            System.out.print(b);  //values in array a1 and a2 are not the same (trying to fix this)
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    System.out.println("\ndone :)");

}

我需要从数据库中检索相同的数组,但无法弄清楚问题。我该解决这个问题吗?

这是我在mysql中创建的表

create table keytable (
n1 varchar(255) not null, 
'key' blob not null); 

0 个答案:

没有答案