Firebird linux создать базу
Утилита isql позволяет создавать базы данных более, чем одним способом. Мы же рассмотрим простой способ создания базы данных в интерактивном режиме, хотя для серьезного использования Вам, скорее всего, потребуется научиться создавать и использовать скрипты. В руководстве Using Firebird имеется отдельная глава, посвященная этому вопросу.
Запускаем isql
Для создания базы данных с использованием утилиты isql в интерактивном режиме, в командной строке перейдите в директорию bin и наберите isql (Windows) или ./isql (Linux):
C:\Program Files\Firebird\Firebird_1_5\bin>isql↵ Use CONNECT or CREATE DATABASE to specify a database
Оператор CREATE DATABASE
Теперь Вы можете создать базу данных. Предположим, что Вы хотите создать базу данных test.fdb и сохранить её в папке data на диске D:
SQL>CREATE DATABASE 'D:\data\test.fdb' page_size 8192↵ CON>user 'SYSDBA' password 'masterkey';↵
Важно
- В отличии от оператора CONNECT , в операторе CREATE DATABASE кавычки вокруг пути к файлу, имени пользователя и пароля являются обязательными .
- Если Вы используете Classic Server под Linux и в пути не указываете имя хоста, будет произведена попытка создать файл базы данных с Вашей учетной записью в Linux в качестве владельца. Может быть это именно то, что Вы и хотите, а может и нет (подумайте о правах доступа, если Вы хотите, чтобы к базе данных мог подключаться кто-то еще). Если же в пути указать, например, localhost:, тогда создавать и влдаеть файлом будет серверный процесс (который в Firebird 1.5 обычно работает от имени firebird).
- В случае использования Classic Server под Windows, Вы должны указывать имя хоста (которое может быть localhost) плюс полный путь к файлу, в противном случае процесс создания закончится неудачей.
Будет создана база данных и через некоторое время вновь появится приглашение SQL. Теперь Вы подключены к новой базе данных и можете создать какие-нибудь объекты в ней.
Чтобы убедиться, что там действительно база данных, выполните запрос:
SQL>SELECT * FROM RDB$RELATIONS;↵
На экран будет выдано большое количество данных! Этот запрос извлекает все строки из системной таблицы, в которой Firebird хранит метаданные для таблиц. « Пустая » база данных на самом деле не очень-то и пустая – она содержит базу данных, которая будет расти, наполняясь метаданными, по мере создания Вами новых объектов в ней.
Для возвращения в командную строку, наберите
За дополнительной информацией об isql обращайтесь к главе 10 Using Firebird: Interactive SQL Utility (isql).
Firebird linux создать базу
In the examples subdirectory of your Firebird installation is a sample database named employee.fdb . You can use this database to “ try your wings ”.
Server name and path
If you move the sample database, be sure you move it to a hard disk that is physically attached to your server machine. Shares, mapped drives or (on Unix) mounted SMB (Samba) filesystems will not work. The same rule applies to any databases that you create.
There are two elements to a TCP/IP connection string: the server name and the disk/filesystem path. Its format is as follows:
The CONNECT statement
Connecting to a Firebird database requires the user to authenticate using a user name and a valid password. Any user other than SYSDBA , root (on Posix systems), or Administrator (on Windows systems, if Firebird runs as this user) needs also to have permissions to objects inside a database. For simplicity here, we will look at authenticating as SYSDBA using the password masterkey .
Using isql
There are several different ways to connect to a database using isql . One way is to start isql in its interactive shell. Go to the bin subdirectory of your Firebird installation and, at that prompt, type the command isql (on Linux: ./isql ) [↵ means “ hit Enter ”]:
C:\Program Files\Firebird\Firebird_1_5\bin>isql↵ Use CONNECT or CREATE DATABASE to specify a database SQL>CONNECT "C:\Program Files\Firebird\Firebird_1_5\examples\employee.fdb"↵ CON>user 'SYSDBA' password 'masterkey';↵
Important
- In isql , every SQL statement must end with a semicolon. If you hit Enter and the line doesn’t end with a semicolon, isql assumes that the statement continues on the next line and the prompt will change from SQL> to CON> . This enables you to spread long statements over multiple lines. If you hit Enter after your statement and you’ve forgotten the semicolon, just type it on the empty line after the CON> prompt and press Enter again.
- If you run Classic Server on Linux, a fast, direct local connection is attempted if the database path does not start with a hostname. This may fail if your Linux login doesn’t have sufficient access rights to the database file. In that case, connect to localhost : / . Then the server process (with Firebird 1.5 usually running as firebird ) will open the file. On the other hand, network-style connections may fail if a user created the database in Classic local mode and the server doesn’t have enough access rights.
- If you run Classic Server on Windows, you must specify a hostname (which may be localhost ) plus a full path, or the connection will fail.
Note
Although single quote symbols are the “ norm ” for delimiting strings in Firebird, double quote symbols were used with the database path string in the above example. This is sometimes necessary with some of the command-line utilities where the path string contains spaces. Single quotes should work for paths that do not contain spaces.
The quotes around “ SYSDBA ” and “ masterkey ” are optional, by the way. Database paths without spaces also don’t need to be quoted.
At this point, isql will inform you that you are connected:
DATABASE "C:\Program Files\Firebird\Firebird_1_5\examples\employee.fdb", User: sysdba SQL>
You can now continue to play about with the employee.fdb database. The characters isql stand for interactive SQL [utility] . You can use it for querying data, getting information about the metadata, creating database objects, running data definition scripts and much more.
To get back to the command prompt type
For more information about isql , see Using Firebird, Chapter 10: Interactive SQL Utility (isql).
Using a GUI client
GUI client tools usually take charge of composing the CONNECT string for you, using server, path, user name and password information that you type into prompting fields. Use the elements as described in the preceding topic.
Note
- It is quite common for such tools to expect the entire server + path as a single string
- Remember that file names and commands on Linux and other Posix command shells are case-sensitive
Creating a database using isql
There is more than one way to create a database using isql . Here, we will look at one simple way to create a database interactively – although, for your serious database definition work, you should create and maintain your metadata objects using data definition scripts. There is a complete chapter in the Using Firebird manual discussing this topic.
Starting isql
To create a database interactively using the isql command shell, get to a command prompt in Firebird’s bin subdirectory and type isql (Windows) or ./isql (Linux):
C:\Program Files\Firebird\Firebird_1_5\bin>isql↵ Use CONNECT or CREATE DATABASE to specify a database
The CREATE DATABASE statement
Now, you can create your new database interactively. Let’s suppose that you want to create a database named test.fdb and store it in a directory named data on your D drive:
SQL>CREATE DATABASE 'D:\data\test.fdb' page_size 8192↵ CON>user 'SYSDBA' password 'masterkey';↵
Important
- In the CREATE DATABASE statement the quotes around path string, username, and password are mandatory . This is different from the CONNECT statement.
- If you run Classic Server on Linux and you don’t start the database path with a hostname, creation of the database file is attempted with your Linux login as the owner. This may or may not be what you want (think of access rights if you want others to be able to connect). If you prepend localhost: to the path, the server process (with Firebird 1.5 usually running as firebird ) will create and own the file.
- If you run Classic Server on Windows, you must specify a hostname (which may be localhost ) plus a full path, or the creation will fail.
The database will be created and, after a few moments, the SQL prompt will reappear. You are now connected to the new database and can proceed to create some test objects in it.
To verify that there really is a database there, type in this query:
SQL>SELECT * FROM RDB$RELATIONS;↵
The screen will fill up with a large amount of data! This query selects all of the rows in the system table where Firebird stores the metadata for tables. An “ empty ” database is not empty – it contains a database which will become populated with metadata as you begin creating objects in your database.
To get back to the command prompt type
For more information about isql , see Using Firebird, Chapter 10: Interactive SQL Utility (isql).
Firebird SQL
Every database management system has its own idiosyncrasies in the ways it implements SQL. Firebird adheres to the SQL standard more rigorously than any other RDBMS except possibly its “ cousin ”, InterBase®. Developers migrating from products that are less standards-compliant often wrongly suppose that Firebird is quirky, whereas many of its apparent quirks are not quirky at all.
Division of an integer by an integer
Firebird accords with the SQL standard by truncating the result (quotient) of an integer/integer calculation to the next lower integer. This can have bizarre results unless you are aware of it.
For example, this calculation is correct in SQL:
If you are upgrading from a RDBMS which resolves integer/integer division to a float quotient, you will need to alter any affected expressions to use a float or scaled numeric type for either dividend, divisor, or both.
For example, the calculation above could be modified thus in order to produce a non-zero result: