Comandos Informix
Comandos Informix
Comandos Informix
database. In the class, you will use this simple user interface to implement you
r project.
Logging in to Informix
You can login Informix from any workstation (solaris) in ICS lab, using your
UNIX account and password.
Enter the following commands to access Informix/DBAccess.
username@rodan% module load informix
username@rodan% dbaccess
Then the Informix DBACCESS screen will pop up.
DBACCESS: Query-language Connection Database Table Session Exit
Use SQL query language.
------------------------------------------------ Press CTRL-W for He
lp --------
DBAccess has multiple levels of menus. The toppest menu (main menu) is s
hown above. You can either use the cursor to move around the menu and select a c
ommand, or use the capital to make the selection. A brief explanation will show
up below the manu. In addition, you can also use the Ctrl-W for more detailed in
formation about the selection.
From the top menu, choose "Connection -> Connect" option to connect to t
he corect database server. You need to select the connection named "rodan_ius_ne
t" for the class project. The username and password for the connection is the sa
me as your ICS UNIX username and password. After the above operations, the follo
wing screen will show up.
SELECT DATABASE >>
Select a database with the Arrow Keys, or enter a name, then press R
eturn.
----------------------- @rodan_ius_net --------- Press CTRL-W for He
lp --------
ics184_group1@rodan_ius_net sysmaster@rodan_ius_net
ics184_group2@rodan_ius_net sysutils@rodan_ius_net
ics184_group3@rodan_ius_net
After logging in Informix/DBAccess, you can start your work on database. Not
e that you can always use CTRL-C to interrupt the current operation and return t
o the upper level menu.
Creating and Selecting Database
Now you need to choose an area to work. You can either create a database for
yourself or select a previously existing database.
The first time you log in, you will have to create a database for yourse
lf.
Continue from the above screen you got after connecting to "rodan_iu
s_net", you choose "sysmaster".
CONNECTION: Connect Disconnect Exit
Connect to a database environment.
----------- sysmaster@rodan_ius_net ------------ Press CTRL-W fo
r Help --------
Now you are in database sysmaster. Note that sysmaster is like the r
oot directory, please do not create anything in there, just use it temporarily t
o create your own database.
Choose "Exit" option to go out from connection menu and return to th
e main menu.
Choose "Database" option. The following screen will show up. This is
the place you do all kinds of operation on database, such as creating a new dat
abase, selecting an existing database, and checking the information of a databas
e.
DATABASE: Select Create Info Drop cLose Exit
Create a new database.
----------- sysmaster@rodan_ius_net ------------ Press CTRL-W fo
r Help --------
Choose "Create" option.
CREATE DATABASE >>ICS184_groupX
Enter the name you want to assign to the new database, then pres
s Return.
----------------------- @rodan_ius_net --------- Press CTRL-W fo
r Help --------
Enter the name of your database as shown above and press Return. Ple
ase replace "X" by your own project group number.
Choose "Dbspace" option and select a dbspace for your database. For
this class use the one named "ics184".
Choose "Exit" and then "Create-new-database" option.
Now you will be in your own database.
If you have already created your own database, you can just select your own
database and enter into it.
Every time after you login Informix/DBAccess, from the above screen you got
after connecting to "rodan_ius_net", simply select your own database ICS184_grou
pX, you will be in your own database. Choose "Exit" option to return the the mai
n menu and continue your work.
Anytime during you are connected to "rodan_ius_net", you can go to the main
menu, select "Database -> Create" option to create a new database, or select "Da
tabase -> Select" option to select an existing database.
Sharing Database among Group
Databases can be considered similar to subdirectories in that they are initially
private to the user who created them. To share a database among your group memb
ers, the creator of the database should run the following SQL command for each m
ember in the group other than the creator. Follow the introduction to Using SQL
Query to run the "grant" command.
grant dba to <username>;
Other group members then can access the database with their own username and pas
sword. For this class, each group uses one database.
Please also use the command "grant connect to projects;" to add an additional us
er, so that the professor and TA can access your database.
Creating a Table
In your database, you can proceed to create and populate tables. From the main m
enu, choose "Table" option. You will see the following screen:
TABLE: Create Alter Info Drop Exit
Create a new table.
--------- ICS184_groupX@rodan_ius_net ---------- Press CTRL-W for Help -----
---
This is the place you do all kinds of operation on tables, such as creating a ne
w table, altering the schema of a table, droping a table, and checking the infor
mation of a table.
To create a table:
Choose "Create" option.
Enter the name of the table after the prompt "CREATE TABLE >> ".
Choose "Add" option to add a new column. Enter the column name, and colu
mn type.
About Index, you can choose "No" not to add index for the column. After
you learn the knowledge of index, you can modify it later.
About Nulls, choose "Yes" to allow the column has null values, or "No" t
o forbid.
Choose "Modify" option to modify the definitions of existing columns.
Choose "Drop" option to remove existing columns.
To alter the structure of existing table
Choose "Alter" option.
Select the name of the table you want to modify.
Choose "Add", "Modify", "Drop", or other options the same as creating a
table to alter the structure of the table.
Using SQL Query
From the main menu, choose "Query-language" option. You will see the following s
creen:
SQL: New Run Modify Use-editor Output Choose Save Info Drop Exit
Enter new SQL statements using SQL editor.
-------- ICS184_groupX@rodan_ius_net ----------- Press CTRL-W for Help -----
---
This is the place you execute SQL query. You can construct a new SQL query, make
modification on the query, and run the query.
New - Erase any previous query and edit a query. Multiple queries can be ent
ered separated by semicolons.
Run - Execute the query
Modify - Reedit the query
Use-editor - Select which editor you want to use. The default choise is "vi"
.
Choose - Let you take an ASCII file containing the commands. The filename sh
ould end in ".sql"
Save - Take the query and save it to a file with extension ".sql"
Info - Give you information on tables you created
Drop - Delete a file with sql commands
To use SQL query,
Choose "New" option
Enter the SQL query
After editing the query, press <escape>
Select "Run" option to execute the SQL query.
Informix SQL Guide
SQL is not case sensitive(for key words). A complete set of informix SQL command
s can be found in Informix Guide to SQL: Syntax and Informix Guide to SQL: Tutor
ial.
In the following introduction, "<>" means that you should replace what is contai
ned in this <> including <> with your own value. For example, <table_name> shoul
d be replaced by the actual table name you want to use.
Creating a Table
To create a simplest table, it is very easy:
Syntax: CREATE TABLE <tableName> (
< list of column definitions including column name and data type
>
);
Example: CREATE TABLE test (
i integer,
s varchar(10)
);
For attributes with other data type, please refer to the date type section o
f the Informix manuals.
For each column, you can also add any of the following property or column-le
vel constraint:
DEFAULT <value> to set the default value.
NOT NULL -- the column value can not be null;
UNIQUE -- the column value can not be duplicated
PRIMARY KEY -- the column acts as key
REFERENCES <refereced table name>(<column name>) -- the columns refer to
a column in another table. The referenced key must have UNIQUE or PRIMARY KEY c
onstraints.
If you have all the above definitions, the order to write it is DEFAULT clau
se the first, then NOT NULL, and other constraints at last.
Example: CREATE TABLE accounts (
acc_num integer PRIMARY KEY,
acc_code integer UNIQUE,
open_date date DEFAULT TODAY
);
You can also specify any of the following table-level constraints:
UNIQUE(<column name>)
DISTINCE (<column name>)
PRIMARY KEY(<column name>)
FOREIGN KEY(<column names>) REFERENCES <refereced table names>(<column n
ame>)
CHECK(<condition>) -- check the constraints be met before data be assign
ed
Example: CREATE TABLE customer (
ssn char(9),
name varchar(20) NOT NULL,
acct integer,
age integer,
PRIMARY KEY(ssn),
FOREIGN KEY(acct) REFERENCES accounts(acc_num),
CHECK ( age>=18 )
);
You can also use CHECK (<conditions>) to check constraints to designate cond
itions that must be met before data can be assigned to a column during an INSERT
or UPDATE statement.
Example: CREATE TABLE people (
id serial PRIMARY KEY,
name varchar(20),
age int CHECK (age>0),
sex char CHECK (sex='M' OR sex='F'),
birthday date,
working boolean,
salary money,
descript text,
CHECK ( (working AND (salary IS NOT NULL)) OR
(NOT working AND salary IS NULL) )
);
Getting Rid of a Table
To remove a table from your database, execute
Syntax: DROP TABLE <tableName>;
We suggest you execute
Example: DROP TABLE test;
Inserting Tuples
Having created a table, we can insert tuples into it. The simplest way to in
sert is with the INSERT command.
Syntax: INSERT INTO < tableName > VALUES( <list of values for all columns,
in order> );
INSERT INTO < tableName > ( <list of column names> )
VALUES( <list of values for columns in the previous list, in ord
er> );
For instance, we can insert the tuple (10, 'foobar') into relation test by e
ither command below:
Example: INSERT INTO test VALUES( 10, 'foobar' );
INSERT INTO test(i,s) VALUES( 10, 'foobar' );
To insert a new tuple into the table, you must make sure not to generate dup
licate values for the columns that form a key.
Loading Bulk Data
Load statement inserts data from a file into an existing table. It does not
overwrite existing data. You cannot add a row that has the same key as an existi
ng row. The format of the data in the file should also follows the required form
at by Informix. The syntax is following:
Syntax: LOAD FROM '<fileName>' DELIMITER '<delimiter>' INSERT INTO <tablen
ame> (<column name list>);
If you don't use DELIMITER to specify your own delimiter, LOAD statement use
s "|" as the default delimiter. The following example load tuple values stored i
n file test.dat into table test:
Example: LOAD FROM 'people.dat' INSERT INTO people(name, age, sex, birthday
, working, salary, descript);
Content of test.dat is:
Tom|22|M|02/12/1978|T|$56,000.00|a good guy|
Mike|40|M|11/30/1960|T|$75,000.00||
Mary|18|F|04/23/1982|F||smart student|
Description:
The order of the column values in the data file should be the same as th
e column name list in the LOAD command.
The values must satisfies the constraints. For example, the sex must be
'M' or 'F', otherwise, the data can not be loaded.
If you don't want to set value to a column, i.e. let the column be defau
lt value or NULL, just put nothing between the delimiters.
Informix server can generate serial number automatically for the column
with SERIAL data type. So, although id is primary key and can not be null value,
you don't need to insert value for it.
For BOOLEAN data value, 't' or 'T' indicates a TRUE value, and an 'f' or
'F' indicates a FALSE value.
The format of the input value for DATE is like 'mm/dd/year'. The year ca
n be 2-digit number if it is in 20th century.
The format of the input value for MONEY is: a leading '$', a comma(,) as
the thousands separator, and a period(.) as the decimal separator.
Getting the Values of a Relation
We can see the tuples in a relation with the command:
Syntax: SELECT * FROM <tableName> WHERE <conditions>;
For instance, after the above create and insert statements, either of the fo
llowing command
Example: SELECT * FROM test where i=10;
SELECT i,s FROM test where i=10;
produces the result
I S
10 foobar
The details of Load command can be found here.
Creating a View(Create View and View name)
You can use CREATE VIEW statement to create a new view based on existing tab
les and views in the database.
Syntax: CREATE VIEW <viewName> (
<list of column names and their data types>
) AS <SELECT list of column names> FROM <tableName> ;
An example of creating view is:
Example: CREATE VIEW student ( id, name )
AS SELECT * FROM test;
Creating an Index
An important technique for improving the performance of queries is to create
indexes. An index on an attribute of a relation allows the database to quickly
find the tuples in the relation with a given value for the indexed attribute.
CREATE INDEX <indexName> ON <tableName> (<a list of key attributes);
For instance, we can create an index on student id in the previous student v
iew.
CREATE INDEX sid_index ON student(id);
It may be useful if the queries involved in the student id such as the follo
wing query:
SELECT *
FROM student
WHERE id = 10;
Using Trigger
A trigger is a database object that automatically sets off a specified set o
f SQL statements when a specified event occurs. You can use CREATE TRIGGER state
ment to create a trigger. It associates SQL statements with a precipitating acti
on on a table. When the precipitating action occurs, the associated SQL statemen
ts are triggered. The precipitating action and the associated action can both be
an INSERT, DELETE, or UPDATE statement. For the associated statements, they can
be performed before or after the triggering statement executes, or for each row
affected by the triggering statement.
CREATE TRIGGER <triggerName>
[ INSERT|DELETE|UPDATE OF <> ON <tableName>
[ BEFORE|AFTER|FOR EACH ROW ] [ WHEN (<condition>) ] ( <statement> );
For instance, we have two tables: account_table and trans_table. Whenever a
new transaction occurs, i.e. a new tuple inserted in trans_table, the correspond
ing balance in the account_table should be updated. The following trigger can ma
ke sure the values in the tables integrated. NEW is reserved for the new table a
fter the triggering statement executed.
CREATE TABLE account_table(
account_no int,
balance float
);
create table trans_table(
account_no int,
trans_no int,
trans_amount float
);
CREATE TRIGGER tran_trigger
INSERT ON trans_table
REFERENCING NEW as new
FOR EACH ROW (
UPDATE account_table SET balance=balance+new.trans_amount
WHERE account_no = new.account_no
);
insert into account_table values (123, 0);
When a new tuple inserted into trans_table, account_table is updated too:
insert into trans_table values (123, 1, 20);
select * from account_table;
produce the following results:
account_no balance
1 20.00000000000
Dynamic SQL
Dynamic SQL allows a program to form an SQL statement during execution, so t
hat the statement can be determined by user input. The action is performed in tw
o steps.
Preparing a statement
It uses PREPARE statement to have the database server examine the statem
ent text and prepare it for execution.
EXEC SQL prepare <statement id> from '<statement>';
Executing prepared SQL
It uses EXECUTE statement to execute the prepared statement.
EXEC SQL execute <statement id> from '<statement>';
For instance, if you want to inquire the information of some students, you c
an use the following dynamic SQL for query:
EXEC SQL BEGIN DECLARE SECTION;
int sid;
char sname[10];
EXEC SQL END DECLARE SECTION;
EXEC SQL prepare query_stud from 'select id,name from student where name
=?';
EXEC SQL execute query_stud into :sid, sname using 'Mike';
printf("Student: (%d, %s)\n", sid, sname);
EXEC SQL execute query_stud into :sid, sname using 'David';
printf("Student: (%d, %s)\n", sid, sname);
The above produces the following results:
Student: (2, Mike)
Student: (9, David)
Embedded SQL(including cursor)
SQL statements can be embedded in the C and COBOL program. In C, all the sta
tement is preceded by "EXEC SQL". There is a detail example in the next section.
A cursor is a special data object that represents the current state of a que
ry. It is used for retrieving multiple resulting rows of query. It is used in 5
steps:
Declaring a Cursor
EXEC SQL DECLARE <cursorName> CURSOR FOR <statement>;
Opening a Cursor
EXEC SQL OPEN <cursorName>;
Fetching Rows
EXEC SQL FETCH <cursorName>;
Closing a Cursor
EXEC SQL CLOSE <cursorName>;
Freeing a Cursor
EXEC SQL FREE <cursorName>;
For instance, the following program lists the information of all student
s.
EXEC SQL BEGIN DECLARE SECTION;
int sid;
char sname[10];
EXEC SQL END DECLARE SECTION;
EXEC SQL DECLARE cursor_stud CURSOR FOR select id,name from student;
EXEC SQL OPEN cursor_stud;
while ( SQLCODE == 0 ) {
EXEC SQL OPEN cursor_stud INTO :sid, :sname;
if ( SQLCODE == 0 )
printf("Student (%d, %s)\n", sid, sname);
}
EXEC SQL CLOSE cursor_stud;
EXEC SQL FREE cursor_stud;
SQLCODE is set to 0 by the database if the select statement is valid, ot
herwise set to 100. It is used to detect the end of data.
Informix Programming Guide
Setting Environment
setenv INFORMIXSERVER rodan_ius_net
setenv PATH $INFORMIXDIR/bin:$PATH
setenv LD_LIBRARY_PATH $INFORMIXDIR/lib:$INFORMIXDIR/lib/esql:$INFORMIXD
IR/lib/dmi:$INFORMIXDIR/lib/c++
ESQL/C
You can use C program with embedded SQL to do the work yourself. To use ESQL
/C, follow the following steps:
Write your own C program with file extension ".ec".
Compile the program with "esql " command. It will produce a ".c" file, a
".o" file, and an "a.out" file. You can also type "esql -o " to have your own e
xecutive file name.
Run your executive program.
The following are some example programs.
Simple example demo.ec Run the program with one parameter: name of the d
atabase you are using. This program first create a table "people" with three col
umns: ssn and age with type of integer, and name with type of char array. Then i
t insert two tuples into the table. And then it get out the values of ssn and na
me of those whose age is less than 40. It makes use of cursor to get the result
values out. After that, it delete the tuples from the table and drop the table i
tself.
More examples can be found in /home/informix/ius/demo/esql. Some slides on u
sing informix from other interfaces is shown here.
C++
In your program, you should include it.h. Informix uses Sun's C++ compiler t
o compile the program. You can modify the Makefile by changing the program name
demo to your own program name, and use make command to compile the program.
The following are some example programs.
Simple example demo.cpp The sample program performs the same functions a
s the sample program in ESQL/C.
Java
By using JDBC to connect to the database, you can write Java program to do y
our project. You need set environment variable CLASSPATH like:
setenv CLASSPATH $INFORMIXDIR/lib/ifxjdbc-g.jar:$CLASSPATH
The following are some example programs.
Simple example demo.java The sample program performs the same functions
as the sample program in ESQL/C. However, it needs user account and password to
create the connection to database.