K
K
Kostya Ivavshchenko2021-03-09 18:53:16
PostgreSQL
Kostya Ivavshchenko, 2021-03-09 18:53:16

Encoding problem with postgresql in IDEA, how to solve?

I have two scripts, the first one creates tables, the second one fills the tables with data

CREATE SCHEMA IF NOT EXISTS sausageShop;

CREATE TABLE IF NOT EXISTS sausageShop.category
(
    id    serial PRIMARY KEY ,
    title VARCHAR NOT NULL
);

CREATE TABLE IF NOT EXISTS sausageShop.product
(
    id          serial PRIMARY KEY ,
    nameProduct VARCHAR(45)      NOT NULL,
    price       DOUBLE PRECISION NOT NULL,
    composition VARCHAR,
    description VARCHAR,
    rating      DOUBLE PRECISION
);

INSERT INTO sausageShop.product (nameProduct, price, description, composition, rating)
VALUES ('Сосиски', 100, 'Небольшие вкусные штучки', '100% курица', 0);
INSERT INTO sausageShop.product (nameProduct, price, description, composition, rating)
VALUES ('Сервелат', 500, 'Классная копченая колбаска', 'Кто-то умер, чтобы попасть туда', 0);
INSERT INTO sausageShop.product (nameProduct, price, description, composition, rating)
VALUES ('Вяленое мясо', 800, 'Оно вкусное', '200% вяленого мяса', 0);
INSERT INTO sausageShop.product (nameProduct, price, description, composition, rating)
VALUES ('Копченное мясо', 683, 'Оно стоит 683 рубля', 'Его ингридиенты стоили 683 рубля', 0);

INSERT INTO sausageShop.category (title)
VALUES ('колбаски');
INSERT INTO sausageShop.category (title)
VALUES ('мяско');

Dalle using JDBC driver connect to postgresql and execute scripts
private static void createDbTables() throws SQLException, FileNotFoundException {
        Connection connection = getDBConnection();
        ScriptRunner sr = new ScriptRunner(connection);
        System.out.println("Инициализируем базу данных PostgreSQL...");
        Reader reader = new BufferedReader(new FileReader
                ("C:\\Users\\Sakura\\IdeaProjects\\SausageShop\\src\\main\\resources\\sqlScripts\\create_tables.sql"));
        try {
            sr.runScript(reader);
        } catch (RuntimeSqlException e){
            System.out.println("нету бд");
            return;
        }
        System.out.println("База данных успешно проинициализированна!");
    }

    private static void generateContentInDbTable() throws FileNotFoundException {
        Connection connection = getDBConnection();
        ScriptRunner sr = new ScriptRunner(connection);
        System.out.println("Заполняем таблицы...");
        Reader reader = new BufferedReader(new FileReader
                ("C:\\Users\\Sakura\\IdeaProjects\\SausageShop\\src\\main\\resources\\sqlScripts\\generate_content.sql"));
        try{
            sr.runScript(reader);
        } catch (RuntimeSqlException e){
            System.out.println("нету бд");
            return;
        }
        System.out.println("Таблицы заполнины исходными данными!");
    }

    private static Connection getDBConnection() {
        Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres?useUnicode=yes&characterEncoding=UTF-8", "postgres", "postgres");
            return connection;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }

But then something happens, either with the encoding in the idea, or something else, and this comes out:
6047999939d80756469013.jpeg
The tables have the same data, but if you directly execute the same scripts through the postgresql console, then the data does not break
Maybe someone knows how this can be fixed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-03-09
Hasanly @azerphoenix

Good afternoon!
Check the encoding used in the database.
Also try to add db connection url ?useUnicode=yes&characterEncoding=UTF-8
For example,

jdbc:postgresql://localhost:5432/example_db?useUnicode=yes&characterEncoding=UTF-8

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question