|
home /
infca /
mb /
oracle
(navigation links)
|
Dancing is silent poetry. Simonides
|
CRUD
CRUD is an acronym for Create, Read, Update and Delete.
It is a set of operations we get servers to execute (POST, GET, PUT and DELETE respectively).
This is what each operation does:
- Create (POST) - make something
- Read (GET)_- get something
- Update (PUT) - change something
- Delete (DELETE)- remove something
Oracle 10g at AIX
Creació
- c:\soft\oracle\setup.exe
- Installation method := "Advanced Installation" ;
- Installation type := "Custom" ;
- Language Selection := "English" + "Spanish" ;
- Specify Home details :
- Name := "Ora10g_BLBRKI00" ;
- Path := "d:\oracle\10.2.0" ;
- Available Product Components :
- Oracle Database 10g 10.2.0.1.0
- Oracle Enterprise Manager Console DB 10.2.0.1.0
- Enterprise Edition options 10.2.0.1.0
- Oracle Advanced Security 10.2.0.1.0
- Oracle Partitioning
- Oracle Spatial 10.2.0.1.0
- Oracle OLAP 10.2.0.1.0
- Oracle Net Services 10.2.0.1.0
- Oracle Call Interface (OCI) 10.2.0.1.0
- Oracle Windows Interfaces 10.2.0.1.0
- Product-specific Prerequisite checks
- Create Database + "Install database software only".
- Summary + "Install" + End of Installation".
Listener
- Inicio + "Net Configuration Assistant"
- Seleccionar "Listener Configuration"
- "Afegir" + <nom> + protocol := "TCP" + Port Number := 1521 ;
BLBRKD00 o BLBRKI00
Crear base de datos
- D:\oracle\product\admin\SID\scripts\
hay que modificar las rutas y los nombres SID de los archivos:
- SID.bat por ejemplo BLBKRI00
- CreateDB.sql
- CreateDBcatalog.sql
- CreateDBfiles.sql
- postDBCreation.sql
-
modificar el archivo: initSID.ora
en la ruta D:\oracle\product\admin\SID\pfile
-
desde la Command Line de MS-DOS:
-
cd D:\oracle\product\admin\SID\scripts
-
ejecutar el script SID.bat
-
sqlplus /nolog
-
connect / as sysdba
-
@CreateDB.sql
-
@CreateDBcatalog.sql
-
@CreateDBfiles.sql
-
@postDBCreation.sql
Servicios
-
revisar el estado de los servicios
-
Configuración de Red : TNSNAMES.ORA y LISTENER.ORA
PATH :="%ORACLE_HOME%\network\admin" ;
Usar los comandos :
- TNSPING <sid>
- LSNRCTL status
- LSNRCTL SERVICES <sid>
Los archivos de configuración de Red en Windows
están en
\oracle\product\10.2.0\network\admin
Entorno
ORACLE_SID (set to the name of your database OEMREP)
ORACLE_HOME (set the the base directory of the software stack)
HLH :
ORACLE_BASE=/wbmde1/product/9.2.0
ORACLE_SID=wbmde1
ORACLE_HOME=/wbmde1/product/9.2.0
Crear Tablespace
CREATE TABLESPACE DAT DATAFILE
'D:\oracle\oradata\BLBRKD00\DAT01.dbf' SIZE 400M AUTOEXTEND ON NEXT 100M MAXSIZE 1024M
LOGGING
DEFAULT STORAGE (
INITIAL 56K
NEXT 56K
MINEXTENTS 1
MAXEXTENTS 2147483645
PCTINCREASE 0
)
ONLINE
PERMANENT;
CREATE TABLESPACE NDX DATAFILE
'D:\oracle\oradata\BLBRKD00\NDX01.dbf' SIZE 200M AUTOEXTEND ON NEXT 100M MAXSIZE 1024M
LOGGING
DEFAULT STORAGE (
INITIAL 56K
NEXT 56K
MINEXTENTS 1
MAXEXTENTS 2147483645
PCTINCREASE 0
)
ONLINE
PERMANENT;
Crear usuario
Manolo :
CREATE USER db_user
IDENTIFIED BY VALUES 'db_pwd'
DEFAULT TABLESPACE DAT
TEMPORARY TABLESPACE TEMP
PROFILE DEFAULT
ACCOUNT UNLOCK;
GRANT CONNECT TO db_user;
GRANT RESOURCE TO db_user;
ALTER USER db_user DEFAULT ROLE ALL;
GRANT UNLIMITED TABLESPACE TO db_user;
ALTER USER db_user
QUOTA UNLIMITED ON NDX
QUOTA UNLIMITED ON DAT;
Sebas :
CREATE USER dbid IDENTIFIED BY dbpw;
GRANT CONNECT TO dbid;
GRANT RESOURCE TO dbid;
GRANT CREATE TABLE TO dbid;
GRANT CREATE SESSION TO dbid; // SQL*Plus: ORA-01045: user WBRKADM lacks CREATE SESSION privilege; logon denied
ALTER USER dbid DEFAULT TABLESPACE brktbspc;
Oracle log file(s)
DOMAIN_NAME\servers\SERVER_NAME\logs\SERVER_NAME.log
Accés a Oracle en AIX
[oracle@rcmqb271]:/wbmpp1> sqlplus "/ as sysdba"
- Envir : ORACLE_HOME & ORACLE_SID
- User AIX := wbrkadm
- SQLPLUS
- Enter user-name: webindes@MQPRE ( usuario Oracle @ instancia de .odbc.ini )
- Enter password:
Data to save
De una instalació ens convé guardar :
- .profile dels diversos usuaris : mqm, wbrkadm, oracle.
- tnsnames.ora, habitualment a {oracle_home}/product/{versio}/network/admin/
- .odbc.ini, habitualment a /var/mqsi/odbc/
- shells de
- MQ
cues, canals
- MB
cfg mgr, broker
TNSNAMES.ORA samples
BLBRKI00=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = IMMQSIA1.intranet.gn.com)(PORT = 1521))
)
(CONNECT_DATA =
(SID = BLBRKI00)
)
)
IMI :
Des = [root@dmqb261]: /wbmde1/product/9.2.0/network/admin>
Pre = [root@rcmqb272]: /wbmpp1/product/9.2.0/network/admin>
Prod = [root@cmqb132]: /wbmpr1/product/9.2.0/network/admin>
LISTENER.ORA samples
D:\oracle\product\10.2.0\NETWORK\ADMIN>type listener.ora
# listener.ora Network Configuration File: D:\oracle\product\10.2.0\network\admin\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = D:\oracle\product\10.2.0)
(PROGRAM = extproc)
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = DMMQSIA3.bcndes.sdg.gn)(PORT = 1521))
)
)
# listener.ora Network Configuration File: D:\oracle\product\10.2.0\network\admin\listener.ora
# Generated by Oracle configuration tools.
BLBRKI00 =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = IMMQSIA1.intranet.gn.com)(PORT = 1521))
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
)
)
SID_LIST_BLBRKI00 =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = D:\oracle\product\10.2.0)
(PROGRAM = extproc)
)
)
HLH :
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL=TCP)(HOST=172.16.16.169)(PORT=1521))
)
)
)
.odbc.ini samples
[ODBC Data Sources]
MQPRE=Oracle9
MQBKPREP=Oracle9
[MQPRE]
Driver=/usr/mqsi/merant/lib/UKor820.so
WorkArounds=536870912
WorkArounds2=2
Description=Oracle9
ServerName=MQPRE
EnableDescribeParam=1
OptimizePrepare=1
[MQBKPREP]
Driver=/usr/mqsi/merant/lib/UKor820.so
WorkArounds=536870912
WorkArounds2=2
Description=Oracle9
ServerName=MQBKPREP
EnableDescribeParam=1
OptimizePrepare=1
[ODBC]
Trace=0
TraceFile=/home/wbrkadm/odbc/trace/odbctrace.out
TraceDll=/usr/mqsi/merant/lib/odbctrac.so
InstallDir=/usr/mqsi/merant
UseCursorLib=0
IANAAppCodePage=4
UNICODE=UTF-8
Un parell de comandes de Oracle (des SQL Plus)
-
veure el nom "logic" de la Base de Dades :
obrir (oracle/ora92/network/admin/) tnsnames.ora => BLBRKD00
-
veure que hi ha accés a la Base de Dades :
TNSPING BLBRKD00 (usuari ora9)
També val
LSNRCTL status
-
veure que hi ha Listener (TNSLSNR.exe at TCPview) :
NETSTAT -AN | grep 1521
i veure quins Serveis manega :
LSNRCTL SERVICES BLBRKD00
-
engegar SQL Plus : U+K+Paràmetre :
Host String := BLBRKD00 as sysdba
If you are connecting to a remote Oracle database,
enter the Oracle Net connect_identifier in the Host String field.
Otherwise, ORA-12560 : TNS: Protocol Adapter error.
-
veure versió de Oracle : TNSPING o
SQL> select * from v$version;
-
veure característiques de la BD :
SQL> select * from v$instance;
-
mostrar camps que té la taula de usuaris :
SQL> desc dba_users;
-
mostrar usuaris :
SQL> select username from dba_users;
-
mostrar camps que té la taula de taules :
SQL> desc dba_tables;
-
mostrar tablespace's existentes en el sistema :
SQL> select tablespace_name from dba_tablespaces;
-
veure els TABLESPACES (amb caracteristiques) :
SQL> select * from v$tablespace;
-
mostrar tablespace's de todos los usuarios :
SQL> select username,default_tablespace from dba_users;
-
mostrar tablespace's de un usuario determinado :
SQL> select username,default_tablespace from dba_users where username='SAG22';
-
mostrar tablespace's :
SQL> select * from dba_users where username='ESBRKP00';
-
mostrar table's de un usuari :
SQL> select count(*) from dba_tables where owner='ESBRKP00';
-
veure la versió del S.O. des SQL :
SQL> SELECT dbms_utility.port_string FROM dual;
-
esborrar un usuari :
SQL> DROP <user_name>
-
engegar Oracle :
[root@cmqb131]:/usr/local/bin> cat start_oracle.sh
su - oracle -c lsnrctl start
echo "connect / as sysdba;" > /tmp/startdb.sql
echo "startup;" >> /tmp/startdb.sql
echo "exit;" >> /tmp/startdb.sql
su - oracle -c "export ORACLE_SID=wbmpr1; sqlplus -s /nolog @/tmp/startdb.sql"
[root@cmqb131]:/usr/local/bin>
-
veure el SID del Oracle :
tx0609-2:/home/wbrkadm # ps -ef | grep pmon
ora9 307428 1 0 Jan 10 - 0:48 ora_pmon_mqpre
ora9 426118 1 0 Jan 10 - 0:48 ora_pmon_mqcert
El SID va després de "ora_pmon_" ...
-
aturar Oracle :
[root@cmqb131]:/usr/local/bin> cat stop_oracle.sh
su - oracle -c lsnrctl stop
echo "connect / as sysdba;" > /tmp/startdb.sql
echo .alter system switch logfile; > /tmp/startdb.sql
echo "shutdown immediate;" >> /tmp/startdb.sql
echo "exit;" >> /tmp/startdb.sql
su - oracle -c "export ORACLE_SID=wbmpr1; sqlplus -s /nolog @/tmp/startdb.sql"
[root@cmqb131]:/usr/local/bin>
després, fer :
[wbrkadm@cmqb131]:/usr/local/bin> ps -ef | grep ora
oracle 217166 1 0 11:25:21 - 0:00 ora_reco_wbmpr1
oracle 332004 1 0 11:25:21 - 0:00 ora_smon_wbmpr1
oracle 491592 1 0 11:25:21 - 0:00 ora_ckpt_wbmpr1
oracle 516286 1 0 11:25:21 - 0:00 ora_lgwr_wbmpr1
oracle 585978 1 0 11:25:21 - 0:00 ora_qmn0_wbmpr1
oracle 598064 1 0 11:25:21 - 0:00 ora_cjq0_wbmpr1
oracle 602124 1 0 11:25:21 - 0:00 ora_s000_wbmpr1
oracle 610466 1 0 11:24:26 - 0:00 /wbmpr1/product/9.2.0/bin/dbsnmp
oracle 622664 1 0 11:25:21 - 0:00 ora_dbw0_wbmpr1
oracle 770186 1 0 11:25:20 - 0:00 ora_pmon_wbmpr1
root 790718 774338 0 11:58:21 pts/4 0:00 grep ora
oracle 794872 1 0 11:25:32 - 0:00 oraclewbmpr1 (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))
oracle 975094 978990 0 11:47:19 pts/3 0:00 -ksh
oracle 995526 1 0 11:25:21 - 0:00 ora_d000_wbmpr1
[wbrkadm@cmqb131]:/usr/local/bin> kill -9 332004
An A-Z Index of Oracle SQL Commands (version 9.2)
Oracle SQLdeveloper
Can Export a Table
in the following formats :
- XML
- CSV
- SQL Insert
- SQL Loader
- Text
DB2 can Import the following formats :
- SQL Scripts (*.clp, *.sql, *.db2)
- Data files (*.dat)
- Text files (*.txt)
- Doc files (*.doc)
- Batch files (*.bat)
- INI files (*.ini)
- "C" files (*.c, *.cpp)
- Header files (*.h, *.hpp)
- Java files (*.java, *.jav)
- HTML files (*.htm, *.html)
- XML files (*.xml)
Problemes i solucions
BIP8146E: Unable to retrieve the SQL primitives supported by the Database.
The command attempted to retrieve the SQL primitives that the Database supports,
however the primitives retrieved indicate that the Database could not be contacted successfully.
Refer to the Administration Guide for information about Database setup,
ensure that the Database libraries are available in the library path
and that the ODBC ini file is correct.
Netejar la cache del Oracle.
ORA-12705 "Invalid NLS parameter"
put AddVMOption -Duser.region=es in \jdev\bin\sqldeveloper.conf
DB2
Engrunes de DB2
An instance provides a logical layer
where you can group multiple databases together,
controlled by a database manager configuration (DBM CFG) file.
A tablespace is a logical layer in which some database objects,
such as tables, views, and indexes, reside.
DB2
concepts :
The DB2 structures from the most to the least inclusive are:
- DB2 tables
Tables are logical structures that DB2 maintains. DB2 supports several different types of tables.
- DB2 indexes
An index is an ordered set of pointers to rows of a table. DB2 can use indexes to improve performance and ensure uniqueness. Understanding the structure of DB2 indexes can help you achieve the best performance for your system.
- DB2 keys
A key is a column or an ordered collection of columns that is identified in the description of a table, an index, or a referential constraint. Keys are crucial to the table structure in a relational database.
- DB2 views
A view is an alternative way of representing data that exists in one or more tables. A view can include all or some of the columns from one or more base tables.
- DB2 schemas and schema qualifiers
The objects in a relational database are organized into sets called schemas. A schema is a collection of named objects that provides a logical classification of objects in the database. The first part of a schema name is the qualifier.
- DB2 storage groups
DB2 storage groups are a set of volumes on disks that hold the data sets in which tables and indexes are stored.
- DB2 databases
DB2 databases are a set of DB2 structures that include a collection of tables, their associated indexes, and the table spaces in which they reside. You define a database by using the CREATE DATABASE statement.
DB2 commands
Shall be issued from DB2 CLP, activated via "c:\Program Files\IBM\SQLLIB\bin\DB2CMD.exe"
DB2LEVEL
Show DB2 Service Level.
c:\Program Files\IBM\SQLLIB\BIN> db2level
DB21085I Instance "DB2" uses "32" bits and DB2 code release "SQL09010" with level identifier "02010107".
Informational tokens are "DB2 v9.1.0.356", "s060629", "NT32", and Fix Pack "0".
Product is installed at "C:\PROGRA~1\IBM\SQLLIB" with DB2 Copy Name "DB2COPY1".
DB2ILIST
Lists all the instances that are available on a system.
DB2 LIST DB DIRECTORY
Lists all databases cataloged in the DB directory.
wbrkadm@lxdwmb01:> db2 list database directory
System Database Directory
Number of entries in the directory = 1
Database 1 entry:
Database alias = DESA01DB
Database name = DESA01DB
Local database directory = /db2mb
Database release level = b.00
Comment =
Directory entry type = Indirect
Catalog database partition number = 0
Alternate server hostname =
Alternate server port number =
db2 list active databases
Will show databases that are active
db2 => list active databases
Active Databases
Database name = STSCDB
Applications connected currently = 1
Database path = C:\DB2\NODE0000\SQL00001\
db2 => quit
db2 create db testing
+
db2 uncatalog db sample
+
db2 catalog database sample on
+
db2 terminate
+
db2 connect to sample user db2admin using db2admin
+
db2 drop database sample
db2 CREATE DATABASE MYTESTDB ON C:
DB2HC
Start Health Center !
DB2 : display what do we have
list database directory - lists databases on DB2 server.
connect to sample user db2admin using db2admin - connects to a db.
list tables - lists tables in the DB.
describe select * from emp_act - lists the structure of a table.
select * from EMP_ACT - list the contents in the table.
list tables for all - show you all of the tables.
DB2 heap size change
Application Heap Size - if you're getting Heap Size errors, then double the size of the heap.
get dbm cfg {for <nom>} - displays the current aslheapsz.
update dbm cfg using aslheapsz 30 - sets the heap size to 30.
DB2 Health Monitor
Issue the following command to shut off the health monitor:
db2 update dbm cfg using HEALTH_MON OFF
Then db2stop and db2start to restart the instance.
If you want to keep the health monitor running, you will need to increase the size of MON_HEAP_SZ to about 2048.
But I would recommend you turn it off.
If you need to diagnose a problem and the SQL return code is not sufficient, look in the db2diag.log file.
Reorganizing tables
First, find which tables might benefit from reorganization:
db2 reorgchk current statistics on table all > "reorgchk.txt"
Those tables are indicated by a "*" in at least one of the tree columns next to the table name.
Use this command:
db2 reorg table tableschema.tablename
url
Una altra versio es :
- conectar-se :
db2 connect to database_alias user id_usuari_admin_db2 using contrasenya
- llistar :
db2 reorgchk update statistics on table all > xyz.out
- millorar - per cada tabla amb "*" a nom_taula :
db2 reorg table nom_taula
- per acabar :
db2 terminate db2rbind nom_base_dades -l db2rbind.out -u admin_db2 -p contrasenya
url
display_db2_port.sh
- set the DB2 environment
$ . ~db2inst1/sqllib/db2profile
- find the service name for DB2 instance.
$ svc=`db2 get dbm cfg | grep SVCENAME | cut -d= -f2 | awk '{print $1}'`
- find the service name that you got from Step 2 in /etc/services
$ grep $svc /etc/services
url
DB2 & Hostname change
See db2nodes.cfg.
Or you can issue "db2start" with options to change "hostname" in that file !
Use db2set, as in:
db2inst1> db2set DB2SYSTEM=newhostname
Use db2set -all to see the current settings.
Any variables with the old hostname must be changed to the new hostname.
-bash-3.2$ db2set -all
[i] DB2COMM=tcpip
[i] DB2AUTOSTART=YES
[g] DB2SYSTEM=portal.demos.hal.com
[g] DB2INSTDEF=db2inst1
[g] DB2ADMINSERVER=db2admin
Problem(Abstract) - with version 8.1 of DB2, if the machine name is changed
post-installation, DB2 fails to start, and produces the following error:
"SQL6048N A communication error occurred during START or STOP DATABASE MANAGER processing".
Cause - a TCP/IP communication error occurred while the START or STOP DATABASE MANAGER command
was trying to establish connection with all the nodes defined in the /home/db2inst1/sqllib/db2nodes.cfg file.
Resolving the problem - do the following:
DB2 Help
db2 => ?
ACTIVATE DATABASE GET/UPDATE DB CFG RECONCILE
ADD CONTACT GET/UPDATE DBM CFG RECOVER
ADD CONTACTGROUP GET DBM MONITOR SWITCHES REDISTRIBUTE DB PARTITION
ADD DATALINKS MANAGER GET DESCRIPTION FOR HEALTH REFRESH LDAP
ADD DBPARTITIONNUM GET NOTIFICATION LIST REGISTER
ARCHIVE LOG GET HEALTH SNAPSHOT REORG INDEXES/TABLE
ATTACH GET INSTANCE REORGCHK
AUTOCONFIGURE GET MONITOR SWITCHES RESET ADMIN CFG
BACKUP DATABASE GET RECOMMENDATIONS RESET ALERT CFG
BIND GET ROUTINE RESET DB CFG
CATALOG APPC NODE GET SNAPSHOT RESET DBM CFG
CATALOG APPN NODE HELP RESET MONITOR
CATALOG DATABASE HISTORY RESTART DATABASE
CATALOG DCS DATABASE IMPORT RESTORE DATABASE
CATALOG LDAP DATABASE INITIALIZE TAPE REWIND TAPE
CATALOG LDAP NODE INSPECT ROLLFORWARD DATABASE
CATALOG LOCAL NODE LIST ACTIVE DATABASES RUNCMD
CATALOG NPIPE NODE LIST APPLICATIONS RUNSTATS
CATALOG NETBIOS NODE LIST COMMAND OPTIONS SET CLIENT
CATALOG ODBC DATA SOURCE LIST DATABASE DIRECTORY SET RUNTIME DEGREE
CATALOG TCPIP NODE LIST DB PARTITION GROUPS SET TABLESPACE CONTAINERS
CHANGE DATABASE COMMENT LIST DATALINKS MANAGERS SET TAPE POSITION
CHANGE ISOLATION LEVEL LIST DBPARTITIONNUMS SET UTIL_IMPACT_PRIORITY
CREATE DATABASE LIST DCS APPLICATIONS SET WRITE
CREATE TOOLS CATALOG LIST DCS DIRECTORY START DATABASE MANAGER
DEACTIVATE DATABASE LIST DRDA INDOUBT START HADR
DEREGISTER LIST HISTORY STOP DATABASE MANAGER
DESCRIBE LIST INDOUBT TRANSACTIONS STOP HADR
DETACH LIST NODE DIRECTORY TAKEOVER
DROP CONTACT LIST ODBC DATA SOURCES TERMINATE
DROP CONTACTGROUP LIST PACKAGES/TABLES UNCATALOG DATABASE
DROP DATABASE LIST TABLESPACE CONTAINERS UNCATALOG DCS DATABASE
DROP DATALINKS MANAGER LIST TABLESPACES UNCATALOG LDAP DATABASE
DROP DBPARTITIONNUM LIST UTILITIES UNCATALOG LDAP NODE
DROP TOOLS CATALOG LOAD UNCATALOG NODE
ECHO LOAD QUERY UNCATALOG ODBC DATA
EDIT MIGRATE DATABASE UNQUIESCE DATABASE
EXPORT PING UNQUIESCE INSTANCE
FORCE APPLICATION PREP/PRECOMPILE UPDATE ALERT CFG
GET/UPDATE ADMIN CFG PRUNE HISTORY/LOGFILE UPDATE COMMAND OPTIONS
GET ALERT CFG PUT ROUTINE UPDATE CONTACT
GET AUTHORIZATIONS QUERY CLIENT UPDATE CONTACTGROUP
GET/UPDATE CLI CFG QUIESCE DATABASE UPDATE NOTIFICATION LIST
GET CONNECTION STATE QUIESCE INSTANCE UPDATE HISTORY
GET CONTACTGROUP QUIESCE TABLESPACES UPDATE LDAP NODE
GET CONTACTGROUPS QUIT UPDATE MONITOR SWITCHES
GET CONTACTS REBIND
Note: Some commands are operating system specific and may not be available.
For further help:
? db2-command - help for specified command
? OPTIONS - help for all command options
? HELP - help for reading help screens
The preceding three options can be run as db2 <option> from an OS prompt.
!db2ic - DB2 Information Center (Windows only)
This command can also be run as db2ic from an OS prompt.
db2 =>
DB2 @ MB
@rem (Re-) Create DB2 Database
@rem *** Change next line as appropriate ***
@set DB2BNDDIR=C:\ARCHIV~1\IBM\SQLLIB\BND
@if '%1'=='' goto usage
@if %1==.db2cmd. goto db2cmd
@db2cmd /i /w /c /t %0 .db2cmd. %1 %DB2BNDDIR%
@goto end
:db2cmd
db2start
@echo Creating %2 ...
DB2 UNCATALOG SYSTEM ODBC DATA SOURCE %2
DB2 DROP DATABASE %2
DB2 CREATE DATABASE %2
DB2 CONNECT TO %2
DB2 BIND %DB2BNDDIR%\@db2cli.lst blocking all grant public
DB2 BIND %DB2BNDDIR%\@db2ubind.lst blocking all grant public
DB2 DISCONNECT %2
@rem Modify database CONFIGURATION values
@rem SET MAXAPPLS to 5000 (this forces a requirement on BUFFPAGE to be raised
@rem to 10000 as it must be at least 2 * MAXAPPLS!)
db2 update db cfg for %2 using buffpage 10000
db2 update db cfg for %2 using maxappls 5000
db2 update db cfg for %2 using dbheap 900
DB2 UPDATE DATABASE CONFIGURATION FOR %2 USING DBHEAP 1024
DB2 UPDATE DATABASE CONFIGURATION FOR %2 USING APP_CTL_HEAP_SZ 1024
DB2 CATALOG SYSTEM ODBC DATA SOURCE %2
DB2 LIST SYSTEM ODBC DATA SOURCES
@goto end
:usage
@echo Create a database for a WBI Configuration Manager or Broker
@echo
@echo Usage: createDB "database name"
@echo
@echo This will:
@echo 1. Create a database
@echo 2. Bind the Client package (see note below)
@echo 3. Set BUFFPAGE, MAXAPPLS, DBHEAP, APP_CTL_HEAP_SZ
@echo 4. Catalogue the database with ODBC
@echo
@echo *** Note: The bind directory is set to %DB2BNDDIR%. Is this correct?
@echo *** If not, you must change the DB2BNDDIR variable at the beginning of this script.
:end
c:\sebas\WS-BI-MB\Emir\Comandos\createDB.cmd
DB2 backup
C:\eines\db2> db2 list database directory | find "Database name"
Database name = OPNACT
Database name = SNCOMM
Database name = HOMEPAGE
Database name = DOGEAR
Database name = PEOPLEDB
Database name = BPC_DB
Database name = LOTUSFOR
Database name = BLOGS
C:\eines\db2> db2 backup DATABASE OPNACT to c:\eines\db2\
SQL1035N The database is currently in use. SQLSTATE=57019
C:\eines\db2>db2 force applications all
DB20000I The FORCE APPLICATION command completed successfully.
DB21024I This command is asynchronous and may not be effective immediately.
C:\eines\db2>db2stop
03/28/2012 12:33:44 0 0 SQL1064N DB2STOP processing was successful.
SQL1064N DB2STOP processing was successful.
C:\eines\db2>db2 backup DATABASE OPNACT to c:\eines\db2\
SQL1032N No start database manager command was issued.
C:\eines\db2>db2start
03/28/2012 12:34:49 0 0 SQL1063N DB2START processing was successful.
SQL1063N DB2START processing was successful.
C:\eines\db2>db2 backup DATABASE OPNACT to c:\eines\db2\
Backup successful. The timestamp for this backup image is : 20120328123500
Errors de DB2 - DB2DIAG.LOG
c:\IBM\SQLLIB\DB2\DB2DIAG.LOG
o
/home/db2inst1/sqllib/db2dump/db2diag.log
Find "panic", "Log file can not be used",
"locked", "damaged", "fatal error", "ERROR_LOCK_VIOLATION", ...
SQLSTATE=57019 => "DB2START"
SQLSTATE=42705 => "DB2 CONNECT TO TKT01DB"
SQLSTATE=58005 => ?
FFST
Problemes ?
- type db2admin command without any arguments. It displays the "DAS" name.
- goto "<db2path>\<DAS name>\dump" directory, as C:\IBM\SQLLIB\DB2DAS00\dump\
- read db2dasdiag.log file
Dubtes de DB2
Dono la comanda "db2stop force" i em surt
"SQL1025N The database manager was not stopped because databases are still active"
Que faig ?
Noticies DB2
DB2 Universal Database Version 9.1 is going out of support as of April 30, 2012
URLs de DB2
DB2 v8 Connectivity
Cheat Sheet
DB2 v9
Fundamentals Certification
DB2
Basic Features and Concepts
DB2
Survival Guide
DB2 Information Center :
v8
v9,
v8 System Commands.
DB2 FixPak site :
DB2 FP 5.
ODBC programming using Apache Derby.
Cloudscape and ODBC
Best practices for tuning DB2 UDB v8.1 and its databases -
McArthur.
Set up DB2 Enterprise 9 on a Linux virtual machine using VMware ESX Server :
url
MySQL @ T400 SLES
Start :
S11TP400:~ # /etc/init.d/mysql start
Creating MySQL privilege database...
Installing MySQL system tables...
OK
Filling help tables...
OK
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h S11TP400.bar.es.hal.com password 'new-password'
Alternatively you can run:
/usr/bin/mysql_secure_installation
which will also give you the option of removing the test databases and anonymous user created by default.
This is strongly recommended for production servers.
See the manual for more instructions.
You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &
You can test the MySQL daemon with mysql-test-run.pl
cd mysql-test ; perl mysql-test-run.pl
Please report any problems with the /usr/bin/mysqlbug script!
The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at http://shop.mysql.com
Updating MySQL privilege database...
Looking for 'mysql' in: /usr/bin/mysql
Looking for 'mysqlcheck' in: /usr/bin/mysqlcheck
Running 'mysqlcheck'...
mysql.columns_priv OK
mysql.db OK
mysql.func OK
mysql.help_category OK
mysql.help_keyword OK
mysql.help_relation OK
mysql.help_topic OK
mysql.host OK
mysql.proc OK
mysql.procs_priv OK
mysql.tables_priv OK
mysql.time_zone OK
mysql.time_zone_leap_second OK
mysql.time_zone_name OK
mysql.time_zone_transition OK
mysql.time_zone_transition_type OK
mysql.user OK
Running 'mysql_fix_privilege_tables'...
OK
Starting service MySQL done
S11TP400:~ #
Lets do it :
S11TP400:~ # /usr/bin/mysqladmin -u root password clau-de-pas
S11TP400:~ #
S11TP400:~ #
S11TP400:~ #
S11TP400:~ # /usr/bin/mysqladmin -u root -h S11TP400.bar.es.hal.com password clau-de-pas
/usr/bin/mysqladmin: connect to server at 'S11TP400.bar.es.hal.com' failed
error: 'Host 'S11TP400.bar.es.hal.com' is not allowed to connect to this MySQL server'
Solució:
# logrotate /etc/logrotate.conf
Per fer-ho permanent:
/etc/cron.daily/logrotate
I hem de configurar :
as stated in /etc/logrotate.d/mysqld file i.e.
# If the root user has a password you have to create a /root/.my.cnf configuration file
# with the following content:
#
# [mysqladmin]
# password = clau-de-pas
# user= root
#
# where "" is the password.
#
# ATTENTION: This /root/.my.cnf should be readable ONLY for root !
Don't forget to
sudo chmod 600 /root/.my.cnf
MySQL log file
# tail -f /var/log/mysqld.log
121211 13:28:00 mysqld started
121211 13:28:00 InnoDB: Started; log sequence number 0 43655
121211 13:28:00 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.0.67' socket: '/var/lib/mysql/mysql.sock' port: 3306 SUSE MySQL RPM
MySQL @ Ubuntu
# sudo apt-get install mysql-server
# vi /etc/mysql/my.cnf file to configure the basic settings -- log file, port number, etc
# sudo netstat -tap | grep mysql
# sudo service mysql restart
sebas@6qserver:/etc/mysql$ /etc/init.d/mysql status
Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service mysql status
sebas@6qserver:$ tail -f /var/log/mysql/mysql.log
Dins de mysql:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yourpassword');
mysql> select user();
+-----------------+
| user() |
+-----------------+
| sebas@localhost |
+-----------------+
1 row in set (0.00 sec)
mysql> SHOW GRANTS FOR sebas;
MySQL @ RH6.1 64-bit
[root@rhv6-64b etc]# cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
MySQL at RH
[root@rhv6-64b ~]# mysql -u sebas
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Solucio : install and start mysqld, mysql daemon : /etc/rc.d/init.d/mysqld start
[root@rhv6-64b etc]# rpm -q mysqld
package mysqld is not installed
Mirem requisits :
[root@rhv6-64b cmds]# rpm -i --test /mnt/dvd/Packages/mysql-server-5.1.52-1.el6_0.1.x86_64.rpm
warning: /mnt/dvd/Packages/mysql-server-5.1.52-1.el6_0.1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY
error: Failed dependencies:
perl-DBD-MySQL is needed by mysql-server-5.1.52-1.el6_0.1.x86_64
Els instalem :
[root@rhv6-64b cmds]# rpm -Uvh /mnt/dvd/Packages/mysql-server-5.1.52-1.el6_0.1.x86_64.rpm /mnt/dvd/Packages/perl-DBD-MySQL-4.013-3.el6.x86_64.rpm
warning: /mnt/dvd/Packages/mysql-server-5.1.52-1.el6_0.1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY
Preparing... ########################################### [100%]
1:perl-DBD-MySQL ########################################### [ 50%]
2:mysql-server ########################################### [100%]
I el engeguem :
[root@rhv6-64b init.d]# ./mysqld start
Initializing MySQL database: WARNING: The host 'rhv6-64b' could not be looked up with resolveip.
This probably means that your libc libraries are not 100 % compatible
with this binary MySQL version. The MySQL daemon, mysqld, should work
normally with the exception that host name resolving will not work.
This means that you should use IP addresses instead of hostnames
when specifying MySQL privileges !
Installing MySQL system tables...
OK
Filling help tables...
OK
To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h rhv6-64b password 'new-password'
Alternatively you can run:
/usr/bin/mysql_secure_installation
which will also give you the option of removing the test
databases and anonymous user created by default. This is
strongly recommended for production servers.
See the manual for more instructions.
You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &
You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl
Please report any problems with the /usr/bin/mysqlbug script!
[ OK ]
Starting mysqld: [ OK ]
Ja podem entrar:
[root@rhv6-64b init.d]# mysql -u sebas
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.52 Source distribution
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MySQL history file
On Unix, the mysql client writes a record of executed statements to a history file.
By default, the history file is named .mysql_history and is created in your home directory.
To specify a different file, set the value of the MYSQL_HISTFILE environment variable.
# cat /home/sebas/.profile
export MYSQL_HISTFILE=/home/sebas/mysql_history.txt
MySQL help
"man mysql" :
MYSQL COMMANDS
mysql sends each SQL statement that you issue to the server to be executed.
There is also a set of commands that mysql itself interprets. For a list of these commands, type help or \h at the mysql> prompt:
mysql> help
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
? (\?) Synonym for `help'.
clear (\c) Clear command.
connect (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter. NOTE: Takes the rest of the line as new delimiter.
edit (\e) Edit command with $EDITOR.
ego (\G) Send command to mysql server, display result vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
help (\h) Display this help.
nopager (\n) Disable pager, print to stdout.
notee (\t) Don't write into outfile.
pager (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print (\p) Print current command.
prompt (\R) Change your mysql prompt.
quit (\q) Quit mysql.
rehash (\#) Rebuild completion hash.
source (\.) Execute an SQL script file. Takes a file name as an argument.
status (\s) Get status information from the server.
system (\!) Execute a system shell command.
tee (\T) Set outfile [to_outfile]. Append everything into given outfile.
use (\u) Use another database. Takes database name as argument.
charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.
For server side help, type 'help contents'
Each command has both a long and short form. The long form is not case sensitive; the short form is.
The long form can be followed by an optional semicolon terminator, but the short form should not.
Mongo-DB
MongoDB
is an open-source, document-oriented database designed for ease of development and scaling.
MongoDB utilizes a simple JavaScript interface for querying.
Looking up a document is as simple as passing a JavaScript object that partially describes the search target.
MongoDB is a document-oriented database, not a relational one.
The primary reason for moving away from the relational model is to make scaling out easier.
Some of the basic concepts of MongoDB:
- a document is the basic unit of data for MongoDB,
roughly equivalent to a row in a relational database management system (but much more expressive).
- similarly, a collection can be thought of as the schema-free equivalent of a table.
- a single instance of MongoDB can host multiple independent databases,
each of which can have its own collections and permissions.
- MongoDB comes with a simple but powerful JavaScript shell,
which is useful for the administration of MongoDB instances and data manipulation.
- every document has a special key, "_id", that is unique across the document's collection.
(1) mongo-db -> (xN) database -> (xN) collections [table] -> (xN) documents [row]
At the heart of MongoDB is the concept of a document:
an ordered set of keys with associated values.
In JavaScript, for example, documents are represented as objects:
{"greeting" : "Hello, world!"}.
This simple document contains a single key, "greeting", with a value of "Hello, world!".
Mongo
scripting,
scripts.
Install RH
Install
manual, done on
RH 64b
Configuration file is /etc/mongod.conf, in conjunction with the control script at /etc/rc.d/init.d/mongod
Data files are stored in /var/lib/mongo and log files in /var/log/mongo
It runs using the mongod user account
Lets run the mongo shell:
[root@rhv6-64b ~]# /usr/bin/mongo
MongoDB shell version: 2.4.5
connecting to: test
Tue Jul 23 11:48:11.023 JavaScript execution failed: Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112
exception: connect failed
[root@rhv6-64b ~]#
Lets start the daemon:
[root@rhv6-64b init.d]# mongod
mongod --help for help and startup options
Tue Jul 23 11:55:41.798 [initandlisten] MongoDB starting : pid=3089 port=27017 dbpath=/data/db/ 64-bit host=rhv6-64b
Tue Jul 23 11:55:41.798 [initandlisten] db version v2.4.5
Tue Jul 23 11:55:41.798 [initandlisten] git version: a2ddc68ba7c9cee17bfe69ed840383ec3506602b
Tue Jul 23 11:55:41.798 [initandlisten] build info: Linux ip-10-2-29-40 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_49
Tue Jul 23 11:55:41.798 [initandlisten] allocator: tcmalloc
Tue Jul 23 11:55:41.798 [initandlisten] options: {}
Tue Jul 23 11:55:41.799 [initandl""isten] exception in initAndListen: 10296
*********************************************************************
ERROR: dbpath (/data/db/) does not exist.
Create this directory or give existing directory in --dbpath.
See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
Tue Jul 23 11:55:41.799 dbexit:
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: going to close listening sockets...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: going to flush diaglog...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: going to close sockets...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: waiting for fs preallocator...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: lock for final commit...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: final commit...
Tue Jul 23 11:55:41.799 [initandlisten] shutdown: closing all files...
Tue Jul 23 11:55:41.799 [initandlisten] closeAllFiles() finished
Tue Jul 23 11:55:41.799 dbexit: really exiting now
[root@rhv6-64b init.d]#
Ens cal un directori (amb 3 GB) o "--smallfiles"
Engeguem amb fitxer de
configuració:
[root@rhv6-64b /home/sebas/reserves/]# cat mongo_start.sh
#!/bin/bash
if [ `id -u` -ne 0 ]
then
echo "--- "$0" must be launched by root"
exit 1
fi
echo "Engegar el Mongo-DB amb un LOG i activant el protocol REST":
/usr/bin/mongod --rest --config /etc/mongod.conf
I la configuració:
[root@rhv6-64b cmds]# cat /etc/mongod.conf
smallfiles = true
logpath=/var/log/mongo/mongod.log
dbpath=/var/lib/mongo
L'engegada es aixi:
[root@rhv6-64b reserves]# ./mongo_start.sh
Engegar el Mongo-DB:
about to fork child process, waiting until server is ready for connections.
forked process: 16316
all output going to: /var/log/mongo/mongod.log
child process started successfully, parent exiting
[root@rhv6-64b reserves]# ps -ef | grep -v grep | grep mongo
root 16316 1 0 12:28 ? 00:00:00 /usr/bin/mongod --rest --config /etc/mongod.conf
How to stop it
The only way is using "kill -15" :
rhv6-64b:sebas >ps -ef | grep mongo
root 3541 1 0 12:29 ? 00:00:00 mongod --config /etc/mongod.conf
[root@rhv6-64b ~]# kill -15 3541
Bona practica per un one-liner and parser, isnt it ?
rhv6-64b:sebas > ps -eo pid,comm | grep mongod
pkill -9 mongod
ps -eo pid,comm | grep mongod
Install W7
Tutorial
Get this
fix 405791
Get code keeping in mind
c:\> wmic os get osarchitecture
OSArchitecture
64-bit
Move all unziped files to c:\mongodb and create mongodb\data\ and mongodb\data\db\ and mongodb\log\.
Create configuration file:
type mongod.cfg
logpath=c:\eines\soft\mongo\log\mongo.log
dbpath=c:\eines\soft\mongo\data\db\
Start mongodb by
start "Mongodb" c:\mongodb\bin\mongod --rest --dbpath c:\mongodb\data\db
or
start "MongoDB" C:\mongodb\bin\mongod.exe --rest --config C:\mongodb\mongod.cfg
Verify it works using the client:
c:\mongodb\bin> mongo
MongoDB shell version: 2.4.6
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see http://docs.mongodb.org/
Questions? Try the support group http://groups.google.com/group/mongodb-user
> db.test.save( { a: 1 } )
> db.test.find()
{ "_id" : ObjectId("523b194f904161bd4a4aa04e"), "a" : 1 }
>
Install it as a windows service if you please:
.\bin\mongod.exe --config C:\mongodb\mongod.cfg --install
Wed Jan 01 15:14:42.187 Trying to install Windows service 'MongoDB'
Wed Jan 01 15:14:42.479 Service 'MongoDB' (Mongo DB) installed with command line
'c:\eines\soft\mongo\bin\mongod.exe --config c:\eines\soft\mongo\mongod.cfg --service'
Wed Jan 01 15:14:42.479 Service can be started from the command line with 'net start MongoDB'
To run the MongoDB service:
net start MongoDB
To stop it
net stop MongoDB
To uninstall it:
C:\mongodb\bin\mongod.exe --remove
Mongo-db server
By default, MongoDB listens for socket connections on port 27017.
To start the server, run the mongod executable, with some parameters:
c:\sebas\JavaScript\vinatxo> type $_start_mongo_for_VINATXO.cmd
start "MongoDB for VINATXO demo" c:\mongodb\bin\mongod.exe --rest --dbpath c:\sebas\JavaScript\vinatxo\data
Mongo-db web admin
mongod also sets up a very basic HTTP server that listens on a port 1,000 higher than
the main port, in this case 28017.
This means that you can get some administrative information about your database
by opening a web browser and going to http://localhost:28017
To make full use of the admin interface (e.g., to access the command list),
you'll need to turn on REST support with --rest when starting Mongo
Server status :
http://localhost:28017/_status
> db.runCommand({"serverStatus" : 1})
Collection contents:
http://127.0.0.1:28017/cdt/wCDT_users/?filter_uAlias=guest
Mongo-db shell
MongoDB comes with a JavaScript shell that allows interaction with a MongoDB instance from the command line.
The shell is very useful for performing administrative functions, inspecting a running instance, or just playing around.
To start the shell, run the mongo executable
The shell is a full-featured JavaScript interpreter, capable of running arbitrary JavaScript programs.
> x = 200
200
> x / 5;
40
> help
HELP
show dbs show database names
use <db name> set current database to <db name>
show collections show collections in current database
show users show users in current database
show profile show recent system.profile entries w. time >= 1ms
db.help() help on DB methods {****}
db.foo.help() help on collection methods {****}
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
db.foo.drop() delete collection, cant use foo anymore
it result of the last line evaluated
Sample:
c:\sebas\JavaScript\> c:\mongodb\bin\mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
admin (empty)
local 0.031GB
winedb 0.031GB
> use winedb
switched to db winedb
> db
winedb
> show collections
system.indexes
wines
> db.wines.find()
{ "name" : "CHATEAU DE SAINT COSME", "year" : "2009", "grapes" : "Grenache / Syrah", "region" : "Rhone", "_id" : ObjectId("539ecc256bf5c3401b42c623") }
{ "name" : "LAN RIOJA CRIANZA", "year" : "2006", "grapes" : "Tempranillo", "country" : "Spain", "region" : "Rioja", "_id" : ObjectId("539ecc256bf5c3401b42c624") }
{ "name" : "Nou vi", "year" : "2009", "_id" : ObjectId("539ed9276bf5c3401b42c62a") }
{ "name" : "Nou vi 2010", "year" : "2010", "_id" : ObjectId("539ed9466bf5c3401b42c62b") }
{ "name" : "Vi del 2014", "year" : "2014", "grapes" : "Garnatxa", "_id" : ObjectId("5465cff362030d3410dccc65") }
>
> db.dropDatabase() // erase the database we have selected right now - see db command
{ "dropped" : "cdt", "ok" : 1 }
> show dbs // "cdt" is gone
local 0.03125GB
>
A good way of figuring out what a function is doing is to type it without the parentheses.
This will print the JavaScript source code for the function.
> db.foo.update
function (query, obj, upsert, multi) {
There is also an autogenerated API of all the JavaScript functions provided by the shell at
http://api.mongodb.org/js, mongo JavaScript API documentation {****}
Fill mongo ddbb from shell
- start mongo
c:\Sebas\JavaScript\test> type $_start_mongo_for_TEST.cmd
set BBDD=nom_db
set COLE=users
start "MongoDB for TEST demo" c:\mongodb\bin\mongod.exe --rest --config c:\Sebas\JavaScript\test\mongod.cfg
- cfg file
c:\Sebas\JavaScript\test> type mongod.cfg
smallfiles=true
logpath=c:\mongodb\log\mongo.log
dbpath=c:\sebas\JavaScript\test\data
- run shell
c:\Sebas\JavaScript\test> type $_crear_bbdd.cmd
set BBDD=nom_db
set COLE=users
mongo localhost:27017/nom_db --quiet my_commands.js
- data from file
c:\Sebas\JavaScript\test> type my_commands.js
db.users.insert({name:"john", email:"john@doe.com", age:12});
db.users.insert({name:"pere", email:"peter@doe.com", age:14});
- show result
c:\Sebas\JavaScript\test> mongoexport -d nom_db -c users
connected to: 127.0.0.1
{ "_id" : { "$oid" : "547cd0c1609aa7f755d78987" }, "name" : "john", "email" : "john@doe.com", "age" : 12 }
{ "_id" : { "$oid" : "547cd0c2609aa7f755d78988" }, "name" : "pere", "email" : "peter@doe.com", "age" : 14 }
Maybe you want to use some
ipsum tool -
Python utils to create random JSON data and import into mongoDB
Populate mongo ddbb from JS
First
code:
// (vinatxo) Populate database with sample data -- Only used once: the first time the application is started.
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server( 'localhost', 27017, {auto_reconnect: true} ) ;
db = new Db( 'winedb', server ) ;
db.open( function( err, db ) {
if( !err ) {
console.log( "Connected to 'winedb' database" ) ;
db.collection( 'wines', { strict:true }, function( err, collection ) { // http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
if ( err ) {
console.log( "{wines.js} The 'wines' collection doesn't exist. Creating it with (2) sample data..." ) ;
populateDB() ;
} ; // if if (err)
} ) ; // db.collection()
} ; // nor ERR
} ) ; // open()
var populateDB = function() {
var wines = [
{
name: "CHATEAU DE SAINT COSME",
year: "2009",
grapes: "Grenache / Syrah",
country: "France",
region: "Southern Rhone",
description: "The aromas of fruit and spice...",
picture: "saint_cosme.jpg"
},
{
name: "LAN RIOJA CRIANZA",
year: "2006",
grapes: "Tempranillo",
country: "Spain",
region: "Rioja",
description: "A resurgence of interest in boutique vineyards...",
picture: "lan_rioja.jpg"
}];
db.collection( 'wines', function( err, collection ) {
collection.insert( wines, {safe:true}, function( err, result) {} ) ; // insert()
});
};
Another code:
exports.adduser = function( db ) {
return function( req, res ) {
// Get our form values. These rely on the "name" attributes
var userName = req.body.username ;
var userEmail = req.body.useremail ;
// Set our collection
var collection = db.get( 'usercollection' ) ;
// Submit to the DB
collection.insert( {
"username" : userName,
"email" : userEmail
}, function ( err, doc ) {
if ( err ) {
// If it failed, return error
res.send( "There was a problem adding the information to the database." ) ;
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location( "userlist" );
// And forward to success page
res.redirect( "userlist" );
}
} ) ; // insert()
} ; // function
} ; // adduser
Tool
Display a collection contents
If BBDD = "testdb" and COLE = "user" then
$ mongoexport -d testdb -c user
$ curl localhost:28017/testdb/user/*
$ mongo testdb --eval db.user.find().forEach(function(x){printjson(x);})
Mongo-db basic data types
Documents in MongoDB can be thought of as "JSON-like"
in that they are conceptually similar to objects in JavaScript.
JSON is a simple representation of data:
the specification can be described in about one paragraph
http://www.json.org proves it
and lists only six data types.
This is a good thing in many ways: it's easy to understand, parse, and remember.
On the other hand, JSON's expressive capabilities are limited, because the only types are
null, boolean, numeric, string, array, and object.
Mongo-db Command Reference
At the time of this writing, MongoDB supports more than 75 different commands,
and more commands are being added all the time.
There are two ways to get an up-to-date list of all of the commands supported by a MongoDB server:
- run db.listCommands() from the shell, or run the equivalent listCommands command from any other driver.
- browse to the
http://localhost:28017/_commands
URL on the MongoDB admin interface (for more on the admin interface see Chapter 8).
Mongo-db access from JavaScript
Which one shall we use ?
- mongodb
univesity !
- monk
Smaller in scope (than mongoose) and thus easier to understand.
Monk is a tiny layer that provides simple yet substantial usability improvements for MongoDB usage within Node.JS
- mongojs
Emulates the official mongodb API as much as possible
- mongoose
connect() sample
Connect():
$ npm install mongojs
// app.js
var databaseUrl = "mydb" ; // "username:password@example.com/mydb"
var collections = [ "users", "reports" ] ;
var db = require( "mongojs" ).connect( databaseUrl, collections ) ;
find() sample
app.get( '/qui_te_reserves/data_Reserva=:dia_consultat', function( req, res ){
var DiaConsultat = req.params.dia_consultat ; // if BLANK then 404 ;
var CollectionName = app.get( 'rcolname' ) ; // get collection name
var MyCollection = db.get( CollectionName ) ; // get the collection
console.log( ">>> GET veure reserves 1 dia - collection (%s) - veure fins a 20 reserves del dia (%s) ", CollectionName, DiaConsultat ) ;
MyCollection.find( { rdata: DiaConsultat }, { limit: 20 }, function( err, docs ){
if ( err ) {
console.log( '--- Veure reserves. Error mongodb is (' + err.message + ').' ) ;
res.status( 500 ) ; // internal error
res.send( {'error':'mongodb error has occurred'} ) ;
} else {
var i = docs.length ;
console.log( "+++ the collection (%s) for the date (%s) has (%s) elements.", CollectionName, DiaConsultat, i ) ;
res.json( docs ) ; // send JSON object
} ; // if Error
}) ; // find()
Mongo-db access from Java
To use mongo from JS we need to start mongo with "--rest"
http://stackoverflow.com/questions/16276557/using-mongodb-from-client-with-javascript
Java + MongoDB
hello world example
Original
documentation
Mongo-db sample in Java
// old version, uses Mongo
Mongo mongo = new Mongo( "localhost", 27017 ) ;
// since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient( "localhost" , 27017 ) ;
Tutorials [****],
hello
Mongo-db access from a browser
See our mongodb contents :
http://127.0.0.1:28017/cdt/wCDT_users/?filter_uAlias=guest
You can query this URL with an AJAX XmlHttpRequest like any webservice.
It will access a database on localhost and return JSON equivalent to a query like this:
yourDatabase.yourCollection.find( {name:"Bob"} ) ;
url
Mongo-db tools
-
exploring Your Database:
-
mongo VUE
-
mongo Hub (mac)
-
use
Robomongo to see what's in the database.
Just download it and connect to your database to see your new users after they signup!
- mongo status every sec
> mongostat
- $ ./mongodump --help
- $ ./mongorestore --help
- $ ./mongoperf.exe -
disk performance
Mongo backup
#!/bin/sh
now=$(date +"%m_%d_%Y")
echo "--host: Host where running MongoDB"
echo "-db: database that you want to backup"
echo "-c: Use the --collection option to specify the collection that you want mongoexport to export"
echo "-out: place where will be located backup"
# Test
mongoexport --host 127.0.0.1:10000 -db MYDB-test -c user -out /DATA/test/my.backup-test.$now.json
# QA
mongoexport --host 127.0.0.1:10001 -db MYDB-qa -c user -out /DATA/qa/my.backup-qa.$now.json
# Prod
mongoexport --host 127.0.0.1:10002 -db MYDB-prod -c user -out /DATA/prod/my.backup-prod.$now.json
# Test. Rm files older then 1 year
find /DATA/test/* -mtime +365 -exec rm {} \;
# QA. Rm files older then 1 year
find /DATA/qa/* -mtime +365 -exec rm {} \;
# Prod. Rm files older then 1 year
find /DATA/prod/* -mtime +365 -exec rm {} \;
url
Mongo access using Java
Using the Java driver is
very simple.
First, be sure to include the driver jar mongo.jar in your classpath.
Go
Java Language Center
and select
Download the Java Driver
In MB Toolkit, right-click on the project name and select "Build Path"
to include it into Java Build Path
Mongo links
SQLITE3
Command line shell,
node module
crear la base de dades
pi@odin:~/llisco $ cat 8_sqlite_1_crear_taula.py
#!/usr/bin/env python
import sqlite3
# http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html
# name of the sqlite database file
sqlite_file = './my_bbdd/llista_de_la_compra.db'
# name of the table to be created
table_name = 'tbl_llisco'
# Connecting to the database file
conn = sqlite3.connect(sqlite_file)
cur = conn.cursor()
# Create a new table with 2 columns
cur.execute('CREATE TABLE '+ table_name +' (numid integer PRIMARY KEY AUTOINCREMENT, producte text NOT NULL)')
# Commit changes and close the connection to the database file
conn.commit()
conn.close()
omplir la base de dades (shell)
Engeguem el codi :
pi@odin:~/llisco $ cat 8_sqlite_2_omplir_taula.sh
sqlite3 ./my_bbdd/llista_de_la_compra.db < ./8_sqlite_8_insert_data.sql
I les dades son :
pi@odin:~/llisco $ cat 8_sqlite_8_insert_data.sql
insert into tbl_llisco values(1,'1 Kg de mandarines');
insert into tbl_llisco values(2,'2 pots de cigrons');
insert into tbl_llisco values(3,'3 ampolles de aigua');
llistar el seu contingut (python)
pi@odin:~/llisco $ cat 8_sqlite_3_mostrar_contingut.py
#!/usr/bin/env python
import sqlite3
conn=sqlite3.connect( './my_bbdd/llista_de_la_compra.db' )
curs=conn.cursor()
print "\nEntire database contents, table tbl_llisco:\n"
for row in curs.execute("SELECT * FROM tbl_llisco"):
print row
conn.close()
acces des nodejs
var sqlite3 = require('sqlite3').verbose();
var dbfilename = "./my_bbdd/llista_de_la_compra.db";
app.get( "/mostrar", function (req, res, next) { // read the data from SQLITE database and send it to client as JSON
console.log( ">>> /mostrar : fer sqlite3 SELECT" ) ;
var mydb = new sqlite3.Database( dbfilename ) ;
mydb.all( "SELECT numid,producte FROM tbl_llisco", function(err, rows) { // get data into "rows"
mydb.close() ;
if (err) return next(err) ;
res.json( rows ) ; // send result as JSON
}); // select
}); // get /mostrar
esborrar la taula
pi@odin:~/llisco $ cat 8_sqlite_9_esborrar_taula.sh
sqlite3 ./my_bbdd/llista_de_la_compra.db "DROP TABLE tbl_llisco ;"
install on w500, win server 2008 R2 standard
how to :
- download ZIP file to C:\eines\soft\sqlite - sqlite-tools-win32-x86-3210000.zip
- extract the content - you shall have sqlite3.exe - C:\eines\soft\sqlite\sqlite-tools-win32-x86-3210000\sqlite3.exe
- get GUI tool for managing SQLite databases : SQLite Studio - sqlitestudio-3.1.1.zip
- extract into C:\eines\soft\sqlite\sqlitestudio-3.1.1\SQLiteStudio\SQLiteStudio.exe
JDBC code
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
// String url = "jdbc:db2://99.137.164.110:50000/edgedb" ;
String url = "jdbc:db2://myjdbc-hostname:50000/edgedb" ;
String user = "db2inst1" ;
String password = "passw0rd" ;
How to select a DDBB
What is the best DDBB for nodejs
- SQLite
This is just a database in a file.
It is very limited at functions, but is great for very small things with small capacity (i.e. Raspberry Pi).
It can really only handle one connection at a time. There is no server. The permissions on the file are its security.
- JSON file
How much do you really need to store? How fast do you need it? How many applications will use it?
If it isn't too too much data, this is a better option than SQLite.
I'm sure there are some NPM libraries that handle it for you.
I usualy just use fs-extra, async, and my own functions. It is extremely easy.
Some packages :
- node-json-db - a simple "database" that use JSON file for Node.JS
- json-file-db - simple file wrapper
to GET, PUT and DELETE javascript objects to files to use with Node.JS [****]
DB tools
-
Per xafardejar els continguts de les bases de dades, ens cal una eina
- com el Toad - tinc v 7.6 i v 8.6 (\\Fonts\).
- SQLdeveloper (Oracle only) - \\Fonts\
- Squirrel -
( open-source Java SQL Client program for any JDBC compliant database ). Yes - DB2 and Oracle.
- dbjmin - open source MULTI-DB client
-
Oracle ODBC test