Warning console code page 866 differs from windows code page 1251

Материал из Кафедра ИУ5 МГТУ им. Н.Э.Баумана, студенческое сообщество

В статье пойдёт речь о том, как добиться корректного вывода кириллицы в «консоли» Windows (cmd.exe).

Описание проблемы

В дистрибутив PostgreSQL, помимо всего прочего, для работы с СУБД входит:

  • приложение с графическим интерфейсом pgAdmin;
  • консольная утилита psql.

При работе с psql в среде Windows пользователи всегда довольно часто сталкиваются с проблемой вывода кириллицы. Например, при отображении результатов запроса к таблице, в полях которых хранятся строковые данные на русском языке.

Ну и зачем тогда работать с psql, кому нужно долбить клавиатурой в консольке, когда можно всё сделать красиво и быстро в pgAdmin? Ну, не всегда pgAdmin доступен, особенно если речь идёт об удалённой машине. Кроме того, выполнение SQL-запросов в текстовом режиме консоли — это +10 к хакирству.

Решение проблемы

Версии ПО:

  • MS Windows 7 SP1 x64;
  • PostgreSQL 8.4.12 x32.

На сервере имеется БД, созданная в кодировке UTF8.

Суть

Суть проблемы в том, что cmd.exe работает (и так будет до скончания времён) в кодировке CP866, а сама Windows — в WIN1251, о чём psql предупреждает при начале работы:

WARNING: Console code page (866) differs from Windows code page (1251)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.

Значит, надо как-то добиться, чтобы кодировка была одна.

В разных источниках встречаются разные рецепты, включая правку реестра и подмену файлов в системных папках Windows. Ничего этого делать не нужно, достаточно всего трёх шагов:

  1. сменить шрифт у cmd.exe;
  2. сменить текущую кодовую страницу cmd.exe;
  3. сменить кодировку на стороне клиента в psql.

Конкретные действия

Супер быстро и просто

Запускаете cmd.exe, оттуда psql:

psql -d ВАШАБАЗА -U ВАШЛОГИН

Далее:

psql \! chcp 1251

Быстро и просто

Запускаете cmd.exe, оттуда psql:

psql -d ВАШАБАЗА -U ВАШЛОГИН

Вводите пароль (если установлен) и выполняете команду:

set client_encoding='WIN866';

И всё. Теперь результаты запроса, содержащие кириллицу, будут отображаться нормально. Но есть небольшой косяк:

Потому предлагаем ещё способ, который этого недостатка лишён.

Посложнее и подольше

Запустить cmd.exe, нажать мышью в правом левом верхнем углу окна, там Свойства — Шрифт — выбрать Lucida Console. Нажать ОК.

Выполнить команду:

chcp 1251

В ответ выведет:

Текущая кодовая страница: 1251

Запустить psql;

psql -d ВАШАБАЗА -U ВАШЛОГИН

Кстати, обратите внимание — теперь предупреждения о несовпадении кодировок нет.

Выполнить:

set client_encoding='win1251';

Он выведет:

SET

Всё, теперь кириллица будет нормально отображаться.

Проверяем:

Hello List,
First time here also beginner to Postgres.So please forgive me for any mistakes.
I'm pretty sure i have same problem.=> http://archives.postgresql.org/pgsql-admin/2012-03/msg00105.php
(After searching it i found it)
However it is not solution for me.:( *I'm pretty sure i'm doing something in wrong manner*.
After issusing that revoke from public my postgres user still able to connect to any database.
More over
  when executing \l user is able to see complete database names.

So i have 2 questions:
1 ) How i can grant my user(s) to connect only to *granted* database not *any*
2 ) Users still able to execute OS (operation system) commands on system.
This is a big security risk.How i can prevent it too.

Any recommendations,manuals,helps,hints,RTFM :P are welcome;)

Thanks in advance.

OS: Windows XP sp2 32 bit+Cygwin.
And here is what i'm doing (For *picture* my situation)






===================BEGIN============================
$ psql -h localhost -U postgres -p 5432
Password for user postgres:
psql (9.1.4)
WARNING: Console code page (866) differs from Windows code page (1251)
          8-bit characters might not work correctly. See psql reference
          page "Notes for Windows users" for details.
Type "help" for help.

postgres=# \dt
No relations found.
postgres=# \l
                                            List of databases
      Name     |  Owner   | Encoding |       Collate       |        Ctype        |   Access privileges
--------------+----------+----------+---------------------+---------------------+-----------------------
  mytestdb     | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  onlypostgres | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  postgres     | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  template0    | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 | =c/postgres          +
               |          |          |                     |                     | postgres=CTc/postgres
  template1    | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 | =c/postgres          +
               |          |          |                     |                     | postgres=CTc/postgres
(5 rows)


postgres=# \dg
                              List of roles
  Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
  postgres  | Superuser, Create role, Create DB, Replication | {}


postgres=# select version() \g
                            version
-------------------------------------------------------------
  PostgreSQL 9.1.4, compiled by Visual C++ build 1500, 32-bit
(1 row)

postgres=# create user testusr with password 'testpwd' \g
CREATE ROLE
postgres=# \dg
                              List of roles
  Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
  postgres  | Superuser, Create role, Create DB, Replication | {}
  testusr   |                                                | {}


postgres=# create database testdb \g
CREATE DATABASE
postgres=# \timing
Timing is on.
postgres=# \c testdb
WARNING: Console code page (866) differs from Windows code page (1251)
          8-bit characters might not work correctly. See psql reference
          page "Notes for Windows users" for details.
You are now connected to database "testdb" as user "postgres".
testdb=# \d
No relations found.
testdb=# create table test_tbl(id serial,somecol text) \g
NOTICE:  CREATE TABLE will create implicit sequence "test_tbl_id_seq" for serial column "test_tbl.id"
CREATE TABLE
Time: 102,137 ms
testdb=# \c
WARNING: Console code page (866) differs from Windows code page (1251)
          8-bit characters might not work correctly. See psql reference
          page "Notes for Windows users" for details.
You are now connected to database "testdb" as user "postgres".
testdb=# \d
                List of relations
  Schema |      Name       |   Type   |  Owner
--------+-----------------+----------+----------
  public | test_tbl        | table    | postgres
  public | test_tbl_id_seq | sequence | postgres
(2 rows)


testdb=# grant all on database testdb to testusr \g
GRANT
Time: 3,638 ms
testdb=# \dg
                              List of roles
  Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
  postgres  | Superuser, Create role, Create DB, Replication | {}
  testusr   |                                                | {}


testdb=# \dp
                                  Access privileges
  Schema |      Name       |   Type   | Access privileges | Column access privileges
--------+-----------------+----------+-------------------+--------------------------
  public | test_tbl        | table    |                   |
  public | test_tbl_id_seq | sequence |                   |
(2 rows)


testdb=# \q

user@SHELL ~
$ psql -h localhost -U testusr -p 5432 -d testdb
Password for user testusr:
psql (9.1.4)
WARNING: Console code page (866) differs from Windows code page (1251)
          8-bit characters might not work correctly. See psql reference
          page "Notes for Windows users" for details.
Type "help" for help.

testdb=> \l
                                            List of databases
      Name     |  Owner   | Encoding |       Collate       |        Ctype        |   Access privileges
--------------+----------+----------+---------------------+---------------------+-----------------------
  mytestdb     | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  onlypostgres | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  postgres     | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 |
  template0    | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 | =c/postgres          +
               |          |          |                     |                     | postgres=CTc/postgres
  template1    | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 | =c/postgres          +
               |          |          |                     |                     | postgres=CTc/postgres
  testdb       | postgres | UTF8     | Russian_Russia.1251 | Russian_Russia.1251 | =Tc/postgres         +
               |          |          |                     |                     | postgres=CTc/postgres+
               |          |          |                     |                     | testusr=CTc/postgres
(6 rows)


testdb=> \c onlypostgres
WARNING: Console code page (866) differs from Windows code page (1251)
          8-bit characters might not work correctly. See psql reference
          page "Notes for Windows users" for details.
You are now connected to database "onlypostgres" as user "testusr".
onlypostgres=> \d
              List of relations
  Schema |    Name    |   Type   |  Owner
--------+------------+----------+----------
  public | wtf        | table    | postgres
  public | wtf_id_seq | sequence | postgres
(2 rows)


onlypostgres=> # WHY THIS testusr is able to connect to all databases? In fact it is not granted for this.:(
onlypostgres(> \r
Query buffer reset (cleared).
onlypostgres=>

onlypostgres=> \! ping google.com

Обмен пакетами с google.com [173.194.71.113] по 32 байт:

Ответ от 173.194.71.113: число байт=32 время=432мс TTL=44
Ответ от 173.194.71.113: число байт=32 время=437мс TTL=44
Ответ от 173.194.71.113: число байт=32 время=437мс TTL=44
Ответ от 173.194.71.113: число байт=32 время=497мс TTL=44

Статистика Ping для 173.194.71.113:
     Пакетов: отправлено = 4, получено = 4, потеряно = 0 (0% потерь),
Приблизительное время приема-передачи в мс:
     Минимальное = 432мсек, Максимальное = 497 мсек, Среднее = 450 мсек
onlypostgres=> # I have also second problem.How i can prevent users to execute OS command?(I don't want users will be
ableto execute OS c 
ommands
onlypostgres'> \r
onlypostgres'># THANKS.
==========================END=======================




On 08/21/2012 02:34 AM, Evil wrote:
> After issusing that revoke from public my postgres user still able to
> connect to any database.

Looking at your logs, you tested to see if they could connect to a
database named "onlypostgres", but I didn't see any sign that you had
REVOKEd connect from public on that database.

Try:

   REVOKE CONNECT ON DATABASE onlypostgres FROM public;

then try to see if you can connect with your test user.

> More over
>   when executing \l user is able to see complete database names.

As far as I know you can't prevent that, it's never been a design goal
to limit which databases a user can see, only to stop them connecting to
them.

Since you want to limit what DBs others can see, I'm guessing you want
to set up a multi-tenanted PostgreSQL install. If so, there are some
limitations on that right now. I strongly suggest that you search the
mailing list archives to learn more.

An option to hide rows in pg_database if the user can't connect to them
sounds simple, but I suspect it'd actually be quite complicated - it'd
effectively require row-level security, something PostgreSQL doesn't
support yet.

You can `REVOKE` `SELECT` rights on the information_schema and some
parts of the system catalog, but that'll probably break `psql`, PgJDBC's
metadata queries, and more.

> 1 ) How i can grant my user(s) to connect only to *granted* database not
> *any*

When you create a database, `REVOKE CONNECT ON DATABASE thedbname FROM
public` on it if you don't want anyone to be able to connect to it.

If you want to make that the default for new databases, connect to
`template1` and revoke connect from public on it. New DBs will inherit
that setting unless they're created with a different template database.

> 2 ) Users still able to execute OS (operation system) commands on system.

Er, WTF?

... ok, looking through that log, you seem to mean this:

> onlypostgres=> \! ping google.com
>
> Обмен пакетами с google.com [173.194.71.113] по 32 байт:

That command is run by the `psql` client. Not the server. Since they're
running `psql` they can already run OS commands, so there's nothing to
prevent.

If they connect remotely over `psql`, the \! commands they run will run
on *their* computer, not the server. Since they can run psql, they can
already run OS commands on their computer, so that doesn't matter.

If they connect remotely over another client like PgAdmin-III, PgJDBC,
psqlODBC, or whatever, they can't run OS commands at all.

--
Craig Ringer




On 20 August 2012 19:34, Evil <evilofrevenge@hotmail.com> wrote:
> Hello List,
> First time here also beginner to Postgres.So please forgive me for any
> mistakes.
> I'm pretty sure i have same problem.=>
> http://archives.postgresql.org/pgsql-admin/2012-03/msg00105.php
> (After searching it i found it)
> However it is not solution for me.:( *I'm pretty sure i'm doing something in
> wrong manner*.
> After issusing that revoke from public my postgres user still able to
> connect to any database.
> More over
>  when executing \l user is able to see complete database names.
>
> So i have 2 questions:
> 1 ) How i can grant my user(s) to connect only to *granted* database not
> *any*
> 2 ) Users still able to execute OS (operation system) commands on system.
> This is a big security risk.How i can prevent it too.
>
> Any recommendations,manuals,helps,hints,RTFM :P are welcome;)

The postgres user is a database superuser.  Trying to prevent it from
connecting to databases is understandably impossible using the GRANT
and REVOKE system, but no end-user should ever connect to the database
cluster as a superuser.  Any operating system commands issued via
"unsafe" procedural languages are only run as the user the database
instance is running as, typically the user "postgres" on the OS, so it
has limited permissions by default.

But here's an example of how to prevent a typical user from connecting
to a database:

postgres=# create database test;
CREATE DATABASE
postgres=# create user test;
CREATE ROLE
postgres=# \c test test
You are now connected to database "test" as user "test".
test=> \c postgres postgres
You are now connected to database "postgres" as user "postgres".
postgres=# revoke connect on database test from public, test;
REVOKE
postgres=# \c test test
FATAL:  permission denied for database "test"
DETAIL:  User does not have CONNECT privilege.
Previous connection kept

You can also set up further connection rules in pg_hba.conf:
http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html

It will even allow you to prevent database superusers from logging in.

Regards

Thom


You appear to have replied directly to me rather than the list, so I've
cc'd the list.

On 08/21/2012 10:11 PM, Evil wrote:
> Dear Craig Ringer  And Dear Thom!
>
> THANK YOU VERY MUCH for such Great and easy explanation!
> Now everything seems is kk with grants.From now i think i understand
> how to separate grants on Postgres.
>
> @Craig Ringer
>
> Forgot about my
>  \! ping google.com
> thing) It is my Epic Fault xD
>
>
> Thanks to you both again for everything.
>



Well, this is one of the most popular interview question for Oracle we are asking (it’s not this straight forward, but for my PostgreSQL level I’ll keep it simple).

The main goal here is to write down basic commands, so I’m leaving aside all management and most of the monitoring questions.

I’d like to say right away that at first I didn’t manage to build usable standby from Windows to Linux due to the default collation that is being used by PostgreSQL on Windows (English_United States.1252) that doesn’t exist in Linux (building it by myself was a bit out of an option, but also a solution), so as a result the replication did start first time, but I wasn’t able to connect to the standby.

Let’s start with creating database with the cross OS compatible collation. PostgreSQL is too small (or badly designed?) to have localization information built-in, so it completely relies on the OS it’s running on. At the same time Microsoft doesn’t give a shit for the standards (like POSIX) even with the late releases, so the only compatible option I found is actually not to use collations a.k.a. “C” collation. Googling doesn’t give many suggestion either. So, let’s create and run PostgreSQL cluster on Windows:

cd "C:\Program Files\PostgreSQL\14\bin"
C:\Program Files\PostgreSQL\14\bin> set PGDATA=C:\Program Files\PostgreSQL\14\data
C:\Program Files\PostgreSQL\14\bin> set PGPORT=5430

C:\Program Files\PostgreSQL\14\bin> initdb -D "C:\Program Files\PostgreSQL\14\data" --locale=C --encoding=UTF8 --username=postgres -W
REM not needed for if the user was specified for the previous command
REM createuser -s postgres

C:\Program Files\PostgreSQL\14\bin> pg_ctl.exe status
pg_ctl: no server running

C:\Program Files\PostgreSQL\14\bin> pg_ctl.exe start
waiting for server to start....2022-03-20 16:15:26.209 GMT [18236] LOG:  redirecting log output to logging collector process
2022-03-20 16:15:26.209 GMT [18236] HINT:  Future log output will appear in directory "log".
...... done
server started

C:\Program Files\PostgreSQL\14\bin> pg_ctl.exe status
pg_ctl: server is running (PID: 18236)
C:/Program Files/PostgreSQL/14/bin/postgres.exe

C:\Program Files\PostgreSQL\14\bin> psql -U postgres
Password for user postgres:
psql (14.2)
WARNING: Console code page (866) differs from Windows code page (1251)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.
Type "help" for help.

postgres=# select version();
                          version
------------------------------------------------------------
 PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit
(1 row)

Now I little bit about my box where I run this setup. It’s a Windows host with running VirtualBox, that is using NAT to connect to the host system, so you will see the same IP address for primary and standby.

Now we will prepare network connectivity settings to be able to run standby (pg_hba.conf is being changed on Windows, the rest run from Linux for my convenience):

REM On Windows:
#pg_hba.conf
#add standby host access control (first for replication itself, second for connection test and to work from Linux)
host    replication     all             192.168.56.1/32         scram-sha-256
host    postgres        all             192.168.56.1/32         scram-sha-256
* 192.168.56.1 is not a real host IP but NAT ip as this way I'm opening my virtual machine

#to apply changes (Windows):
pg_ctl.exe reload

#connection test here (Linux):
[postgres@localhost ~]$ psql -U postgres -h 192.168.56.1 -p 5430 <<<"select version();"
Password for user postgres:
                          version
------------------------------------------------------------
 PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit
(1 row)

#Creating user to run replication (Linux):
[postgres@localhost ~]$ psql -U postgres -h 192.168.56.1 -p 5430 <<<"create user repuser replication login encrypted password 'blaBla61A' connection limit -1;"
Password for user postgres:
CREATE ROLE

I promise you that we are half way there))) There are few database parameters must be set in order to enable replication (some additional queries are to show how to deal with parameters):

parameters on primary:

postgres=# select name,pending_restart,boot_val,setting from pg_settings where name in ('listen_addresses','wal_level','archive_mode','archive_command','max_wal_senders','hot_standby');
       name       | pending_restart | boot_val
------------------+-----------------+-----------
 archive_command  | f               |
 archive_mode     | f               | off
 hot_standby      | f               | on
 listen_addresses | f               | localhost
 max_wal_senders  | f               | 10
 wal_level        | f               | replica
(6 rows)

should be:

postgres=# alter system set archive_command=true;
ALTER SYSTEM
postgres=# alter system set archive_mode=on;
ALTER SYSTEM
postgres=# alter system set wal_level='hot_standby';
ALTER SYSTEM
postgres=# alter system set listen_addresses='*';
ALTER SYSTEM
postgres=# alter system set hot_standby=on;
ALTER SYSTEM
postgres=# alter system set max_wal_senders=3;
ALTER SYSTEM

postgres=# select pg_reload_conf();
 pg_reload_conf
----------------
 t
(1 row)

postgres=# select name,pending_restart,boot_val,setting from pg_settings where name in ('listen_addresses','wal_level','archive_mode','archive_command','max_wal_senders','hot_standby');
       name       | pending_restart | boot_val
------------------+-----------------+-----------
 archive_command  | f               |
 archive_mode     | t               | off
 hot_standby      | f               | on
 listen_addresses | f               | localhost
 max_wal_senders  | t               | 10
 wal_level        | f               | replica
(6 rows)

--restart is needed

C:\Program Files\PostgreSQL\14\bin>pg_ctl.exe stop
waiting for server to shut down.... done
server stopped

C:\Program Files\PostgreSQL\14\bin>pg_ctl.exe start
waiting for server to start....2022-03-20 17:14:15.367 GMT [9600] LOG:  redirecting log output to logging collector process
2022-03-20 17:14:15.367 GMT [9600] HINT:  Future log output will appear in directory "log".
 done
server started

postgres=# select name,pending_restart,boot_val,setting from pg_settings where name in ('listen_addresses','wal_level','archive_mode','archive_command','max_wal_senders','hot_standby');
       name       | pending_restart | boot_val  | setting
------------------+-----------------+-----------+---------
 archive_command  | f               |           | true
 archive_mode     | f               | off       | on
 hot_standby      | f               | on        | on
 listen_addresses | f               | localhost | *
 max_wal_senders  | f               | 10        | 3
 wal_level        | f               | replica   | replica

Now we are directly backing up database as copy directly TO standby (that is pretty nice option), then we are adding/fixing few parameter on standby and starting the cluster itself in replication mode:

#on Linux PGSQL doesn't install with prebuild database, but if you managed to build one already, let's do some cleaning:
#on standby (no data, no cluster/instance should be running):
[root@localhost ~]# systemctl stop postgresql-14.service
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ rm -fr /var/lib/pgsql/14/data/*

#the nice backup option I mentioned
#from standby run backup (aka duplicate for standby):
pg_basebackup -U repuser -h 192.168.56.1 -p 5430 -D /var/lib/pgsql/14/data
#*password from the create user command few step above

#we may or may not fix pg_hba.conf for role transition
#vi /var/lib/pgsql/14/data/pg_hba.conf (10.0.2.15 again is a local address but due to NAT it's the same - and in general #this is for role transition)
#host    replication     all             10.0.2.15/32            scram-sha-256
#host    postgres        all             10.0.2.15/32            scram-sha-256

#from some point in time PG started relay on this file to mark site for replication (bad design again?, why not a parameter that is possible to control using alter system command?)
touch /var/lib/pgsql/14/data/standby.signal

#being lazy a bit and adding parameters the following way:
[postgres@localhost ~]$ cat /var/lib/pgsql/14/data/postgresql.auto.conf
primary_conninfo = 'host=192.168.56.1 port=5430 user=repuser password=blaBla61A'
promote_trigger_file= '/var/lib/pgsql/trigger_file'

#the original configuration file has Windows specific parameter, that must be fixed:
[postgres@localhost ~]$ cat /var/lib/pgsql/14/data/postgresql.conf
dynamic_shared_memory_type = posix

#and the final replication start:
[root@localhost ~]# systemctl start postgresql-14.service

So we are there. Trust me, please) If not, then here is a usual replication test:

#primary:
postgres=# create database test;
CREATE DATABASE
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# create table tettbl as select 1 c1, 'abc' c2;
SELECT 1

#standby check:
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# select * from tettbl;
 c1 | c2
----+-----
  1 | abc
(1 row)

And here is another pretty important query to control lag:

#check lag on primary:
postgres=# select client_addr, write_lag, flush_lag, replay_lag, reply_time from pg_stat_replication;
 client_addr  | write_lag | flush_lag | replay_lag |          reply_time
--------------+-----------+-----------+------------+-------------------------------
 192.168.56.1 |           |           |            | 2022-03-21 18:07:07.382337+00
(1 row)

Footnote (PG style)

Please be aware that such setup is rather useless as it can’t be used for migrations (as for Oracle this can be used) due to mismatch in collation and for real replication (I guess tablespaces will be a pain for such setup).


3

ответов

\! chcp 1251

Ещё, возможно, \encoding windows1251
но это, кажэтся, необязательно (и так включилось, само, по умолчанию).

Работать будет более-менее, но запросы, возвращающие символы не из windows-1251 будут падать.

Ещё можно в настройках региональных стандартов в панэли управления windows (они жэ «Изменение форматов даты, времени и чисел»), на вкладке «Дополнительно» в диалоговом разделе окна «Язык программ, не поддерживающих Юникод» по кнопке «Изменить язык системы» нажать галочку «Использовать Юникод (UTF-8) для поддержки языка во всем мире».

Тогда будут показываться примерно все международные символы, но пропадёт ввод русских букв.
(Это обычно нормально, поскольку символы в базе могут попадаться всякие — а много ли русских данных надо вводить с терминала?)

Ну, и третий вариант — поставить wsl, в нём postgres и подключаться из него. Там всё работает.

test=# \l+
╤яшёюъ срч фрээ√ї
╚ь | ┬ырфхыхЎ | ╩юфшЁютър | LC_COLLATE | LC_CTYPE | ICU Locale | Locale Provider | ╧Ёртр фюёЄєяр | ╨рчьхЁ | ╥рсы. яЁюёЄЁрэёЄтю | ╬яшёрэшх
————+———-+————+————+———-+————+——————+——————+———+———————+———————————————




test=# \q

set LANG=C

>psql test
psql (15devel-MY-EXTRA-VERSION)
WARNING: Console code page (866) differs from Windows code page (1251)
8-bit characters might not work correctly. See psql reference
page «Notes for Windows users» for details.
Type «help» for help.

test=# \l+
List of databases
Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges | Size | Tablespace | Description
————+——-+———-+———+——-+————+——————+——————-+———+————+———————————————

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?


Rꙮman Yankꙮvsky


29

А вообще, что может смущать в самой Julia — бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как «хаки» и произвол. Короче говоря, с…


Viktor G.


2

30500 за редактор? )


Владимир


47

а через ESC-код ?


Alexey Kulakov


29

Чёт не понял, я ж правильной функцией воспользовался чтобы вывести отладочную информацию? но что-то она не ловится


notme


18

У меня есть функция где происходит это:
write_bit(buffer, 1);
write_bit(buffer, 0);
write_bit(buffer, 1);
write_bit(buffer, 1);
write_bit(buffer, 1);
w…


~


14

Добрый день!
Скажите пожалуйста, а какие программы вы бы рекомендовали написать для того, чтобы научиться управлять памятью?
Можно написать динамический массив, можно связный …


Филипп


7

Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех «ибешни…


Alex Sherbakov


5

Ребят в СИ можно реализовать ООП?


Николай


33

https://github.com/erlang/otp/blob/OTP-27.1/lib/kernel/src/logger_h_common.erl#L174
https://github.com/erlang/otp/blob/OTP-27.1/lib/kernel/src/logger_olp.erl#L76

15 лет назад…


Maksim Lapshin


20


Форум программистов Vingrad

Модераторы: LSD

Поиск:

 Как начать? Я полный 0 с БД 

   

Опции темы

Forsaken
Дата 23.4.2010, 16:59 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

Здравствуйте.
Приступил к освоению JDBC и SQL. Решил поставить PostgreSQL 8.4.3-1 для windows (у меня 7-я версия). Но что делать дальше я не знаю, самое главное прочесть нигде не могу самые основы работы с ней. В мануале все было понятно до раздела 1.3. Creating a Database, а именно до этого момента:

Цитата
To create a new database, in this example named mydb, you use the following command: 

$ createdb mydb

Ничего несказанно о том куда собственно вводить $ createdb. Пытался запустить SQL Shell — не выходит..(

Подскажите пожалуйста, с чего начать?

п.с.
никогда не работал с базами данных, разве что немного знаю теорию реляционных БД
Прошу прощения у модераторов за такой пост. Я в тупике

 
skyboy
Дата 23.4.2010, 20:06 (ссылка)
| (нет голосов)
 Загрузка …

неОпытный

Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск

Репутация: 1
Всего: 260

есть консольный shell в комплекте(не знаю, что значит «не выходит»: с какими параметрами ты его запускал, что оно тебе выдало?). есть куча сторонних front end’ов. под windows, под linux, вебовые.
берешь любой из них, подключаешься, вводишь команду($ — это символ приглашения к вводу команды, чтоб ты в мануале видел, где начинается команда; вводить этот символ не надо), выполняешь, смотришь на результат(сообщение об успешном выполнении или ошибке).
не забудь убедиться, что сервер запущен(скорее всего, postgresql при установке создало свою службу — Панель управления/Администрирование/Службы — надо убедиться, что служба запущена)

 
Forsaken
Дата 23.4.2010, 21:25 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

skyboy
Спасибо большое за ответ! Я честно сказать смутновато понял что значит frontend (т.е. я понял что это клиентское приложение, но до него у меня еще дело не дошло)
Короче чтобы не обострять ситуацию, последовательно распишу что я делаю.
Я читаю о JDBC и в самом начале предлагается установить и запустить БД чтобы начать изучать синтаксис SQL и взаимодействие через  JDBC.
1)Выбрал и скачал postgreSQL.
2)Запускаю инсталляцию. В первом коне просто жму Next >
3)Во втором окне оставляю путь по умолчанию: C:\Program Files (x86)\PostgreSQL\8.4
4)В третьем окне также оставляю путь по умолчанию: C:\Program Files (x86)\PostgreSQL\8.4\data
5)В четвертом окне указываю пароль «administrator» и подтверждаю его.
6)В пятом окне оставляю порт 5432
7)В шестом окне выбираю Locale: Russian, Russia, оставляю выбранным Install pl/pgsql in template1 database?
8)Начинаю установку (Next).
9)После установки Stack Builder запускать не стал.
10) Убедился в том что служба postgresql-8.4 работает (Вход от имени .\postgres)
-что теперь делать представляю смутно, но в мануале написано «Для создания новой базы данных, в этом примере называющейся mydb, вы можете использовать следующую команду:

Код

$ createdb mydb

11)запускаю SQL Shell и ввожу:

Код

Server [localhost]: 127.0.0.1
Database [postgres]: postgres
Port [5432]: 5432
Username [postgres]: postgres
Password for user postgres: -не дает ничего ввести-

А дальше я не знаю что вообще делать. Подскажите пожалуйста, что я не сделал?

Это сообщение отредактировал(а) Forsaken — 23.4.2010, 22:17

 
skyboy
Дата 23.4.2010, 22:28 (ссылка)
| (нет голосов)
 Загрузка …

неОпытный

Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск

Репутация: 1
Всего: 260

Цитата(Forsaken @  23.4.2010,  20:25 )
 -не дает ничего ввести-

это консольная программа, верно? там при вводе пароля он просто не отображается. надо ввести пароль «вслепую» и нажать enter. дальше должен заметить: строка приглашения к вводу команды изменится — ты «залогинишься».

Цитата(Forsaken @  23.4.2010,  20:25 )
В четвертом окне указываю пароль «administrator» и подтверждаю его.

что за «четвертое окно» не в курсе, но, возможно, именно этот пароль и надо вводить по запросу SQL Shell. А имя пользователя — root/admin/postgres — тоже не знаю, какой надо. смотри на этом «четвертом окне».

 
Forsaken
Дата 23.4.2010, 22:36 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

skyboy, спасибо все понял.. Действительно ввод пароля без эхо, хотя могли бы отображать звездочки как вдругих программых.. Ну да ладно..
Оболочка очень странно себя ведет и приглашение для ввода совсем непохоже на то что я видел в документации и на картинках..

Код

Server [localhost]: localhost
Database [postgres]: postgres
Port [5432]: 5432
Username [postgres]: postgres
Password for user postgres:
psql (8.4.3)
WARNING: Console code page (866) differs from Windows code page (1251)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.
Type "help" for help.

postgres=# createdb mydb
postgres-# sdflsdjf
postgres-# fuck!
postgres-#

что значит postgres-#, а где же $? Как ему скормить команду createdb?

А туда ли я вообще собираюсь скормить команду 

Код

$ createdb mydb 

?

Это сообщение отредактировал(а) Forsaken — 23.4.2010, 22:41

 
skyboy
Дата 23.4.2010, 23:07 (ссылка)
| (нет голосов)
 Загрузка …

неОпытный

Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск

Репутация: 1
Всего: 260

Цитата(Forsaken @  23.4.2010,  21:36 )
А туда ли я вообще собираюсь скормить команду 

угу. к сожалению, с особенностями синтаксиса pgsql не знаком практически. надо читать примеры работы именно с SQL Shell. может статься, что ему для определения конца команды надо «;» как в mysql. потому этот набор:

Цитата(Forsaken @  23.4.2010,  21:36 )
postgres=# createdb mydb
postgres-# sdflsdjf
postgres-# fuck!

воспринимался как одна многострочная команда, потому и не было сообщения об ошибках при выполнении второй и третьей строки.
а вообще, я тебе ссылки на программы давал. поставь pgAdmin, он с GUI и насчет ошибок там однозначно должно показывать сообщения — выполнено/не выполнено.
с SQL хоть ранее работал?

 
Forsaken
Дата 24.4.2010, 05:45 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

skyboy
Спасибо за помощь!
с SQL к сожалению не работал, вот только подошел к началу изучения.

Цитата
воспринимался как одна многострочная команда, потому и не было сообщения об ошибках при выполнении второй и третьей строки.
а вообще, я тебе ссылки на программы давал. поставь pgAdmin, он с GUI и насчет ошибок там однозначно должно показывать сообщения — выполнено/не выполнено.

У меня стоит pgAdmin, но хотелось бы изучить документацию и выполнить от туда примеры. Но там сразу после теории предлагается ввести команду $ createdb mydb, а куда ее воодить не пойму. Т.е. в этом вся суть пробелмы.

 
skyboy
Дата 24.4.2010, 07:54 (ссылка)
| (нет голосов)
 Загрузка …

неОпытный

Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск

Репутация: 1
Всего: 260

та правильно ты вводишь. вот только тебе должно быть сообщение: либо ошибка, либо «база создана». потому и говорю — лучше поставить pgAdmin, Это тот же SQL Shell, но с GUI. и если ты нажимаешь на пункт меню «выполнить запрос», ты уверен, что запускаешь запрос. А тут, нажимая Enter, без какого-никакого опыта работы, не знаешь, чего ждать

 
Forsaken
Дата 24.4.2010, 08:11 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

skyboy
Я облажался… $ createdb mydb  это команда like-UNIX шелла типа bash или csh, а я пытаюсь ее скормить для psql и естественно он ее непонимает. Т.е. для psql нужны команда SQL сервера.
Эх.. найтибы чтонибудь для начинающего… т.е. совсем…

skyboy
Спасибо за помощь!

 
skyboy
Дата 25.4.2010, 16:42 (ссылка)
| (нет голосов)
 Загрузка …

неОпытный

Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск

Репутация: 1
Всего: 260

а, значит, createdb — это отдельная  программа из пакета. сорри, не знал.
а SQL-вариант, который выполнился бы из SQL-shell, должен выглядеть как «CREATE DATABASE …»

 
Forsaken
Дата 29.4.2010, 15:08 (ссылка)
| (нет голосов)
 Загрузка …

Бывалый

Профиль
Группа: Участник
Сообщений: 193
Регистрация: 30.12.2008

Репутация: нет
Всего: 3

skyboy, ага.. уже дело пошло.. изучаю SQL, вроде пока с Postgres проблем ни каких.
Еще раз спасибо за помощь!

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | PostgreSQL | Следующая тема »

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как вернуть настройки мыши по умолчанию windows 10
  • Как передать изображение с телефона на ноутбук через wifi windows 10
  • Ничего не открывается на компьютере windows 10
  • Microsoft windows server 2019 essentials
  • Windows 10 set user password