K
K
Kamikaze10242017-11-27 15:11:44
Java
Kamikaze1024, 2017-11-27 15:11:44

How to save a field with Cyrillic in cp866 encoding to the database?

Colleagues, I have a database with fields encoded in cp866. It is not possible to save the data in the encoding so that they are written to the database correctly. How can I do it?

Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:configDb.db");

            c.setAutoCommit(true);
            System.out.println("Opened database successfully");

            Statement stmt    = null;

            for(int i = 1; i < table.size(); i++){
                String query = "";
                if(table.get(i).get(2).equals("12")){
                    /*pstmt.setString(1,
                            new String(table.get(i).get(1).getBytes(Charset.forName("cp866"))));*/
                    /*query = "UPDATE CONFIG SET " + table.get(i).get(0) + "='"
                            + new String(table.get(i).get(1).getBytes(Charset.forName("cp866"))) + "' WHERE ID=1";*/

                    Charset cset = Charset.forName("CP866");
                    ByteBuffer buf = cset.encode(table.get(i).get(1));
                    byte[] charsCp866 = buf.array();
                    String value = new String(charsCp866);

                    query = "UPDATE CONFIG SET " + table.get(i).get(0) + "='"
                            + value + "' WHERE ID=1";
                } else if(table.get(i).get(2).equals("4")) {
                    //pstmt.setInt(1, Integer.valueOf(table.get(i).get(1)));
                    /*query = "UPDATE CONFIG SET " + table.get(i).get(0) + "="
                            + new String(table.get(i).get(1).getBytes(Charset.forName("cp866"))) + " WHERE ID=1";*/

                    Charset cset = Charset.forName("CP866");
                    ByteBuffer buf = cset.encode(table.get(i).get(1));
                    byte[] charsCp866 = buf.array();
                    String value = new String(charsCp866);

                    query = "UPDATE CONFIG SET " + table.get(i).get(0) + "="
                            + value + " WHERE ID=1";
                } else {
                    query = "";
                }

                PreparedStatement pstmt = c.prepareStatement(query);
                if(query.equals("")) {
                    System.out.println("Error in creating query!");
                    continue;
                }

                pstmt.executeUpdate();
                pstmt.close();
            }

            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
        System.out.println("Operation done successfully");
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question