Showing posts with label Oracle. Show all posts
Showing posts with label Oracle. Show all posts

Saturday, August 11, 2012

How to Install Oracle SQL Plus on Ubuntu 12.04

On my day to day work I have to deal with Oracle a lot! and since I am trying to use Ubuntu as my working environment I had to install a bunch of things one of them is SQL Plus. I like command line a lot and SQL plus is the best tool for Oracle so I had to have it.

The process is not so complicated. So let's start first you need to go to the Database Instant Client page and download the one specific to your platform. This post is for 32 bit so you have to download the Instant Client Downloads for Linux x86 one. It should be the same for the 54 bit though. From there you need to download these 2 rpm files:
  • Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications
  • Instant Client Package - SQL*Plus: Additional libraries and executable for running SQL*Plus with Instant Client
If you want, you can download the SDK :
  • Instant Client Package - SDK: Additional header files and an example makefile for developing Oracle applications with Instant Client
Since these are rpm files we need to convert them to deb, in order to that we need to install the alien utility
sudo apt-get install alien

Once that is done, go to the folder where the rpm files are located and execute the following
alien -i oracle-instantclient-basic*.rpm
alien -i oracle-instantclient-sqlplus*.rpm
alien -i oracle-instantclient-devel*.rpm

These commands will convert the rpm files on the fly and install them. Now you can test it by just typing sqlplus on the command line. For sure it will complain about a couple of things. One of them maybe about a missing libaio.so.1 . This one is easy, we just need to install it a simple
sudo apt-get install libaio1
The next error might be about missing libraries like libsqlplus.so. The libraries are there but SQL Plus can't find them. We need to add them to our PATH this is easy as well. We just need to create an oracle.conf file inside /etc/ld.so.conf.d/ so lets do that. I use vi because I like it, but you can use whichever editor you want to create the file.
sudo vi /etc/ld.so.conf.d/oracle.conf
then we add this:
/usr/lib/oracle/11.2/client/lib/
Notice that in my path I have 11.2 be careful with this. You can navigate and check that the path is correct for yours. 11.2 is the version we are installing. At the time of this post 11.2 was the latest one. Once you save the file we need to update the configuration by running:
sudo ldconfig

Now you should be ready to connect using:
sqlplus username/password@//dbhost:1521/SID

If you have problems with the SDK, you can check this post.
Hope it helps someone and happy coding!

Tuesday, August 9, 2011

Importing length fixed data in Oracle

These days I have been working a lot with Oracle, usually I have to deal with MS SQL Server, Oracle, MySQL and PostgreSQL so sometimes I get confused and sometimes I missed functionality from other DB engines. Anyways, this time I want to show how to import huge amount of data using sqlldr.

Explain sqlldr in one post is impossible so I will just focus in one part. When you import data usually you get a nice formatted csv file, you know, coma separated or something like that, but what do you do when you just get a huge amount of text?, no comma, tab, quotes separated, nothing! well, if you have the table structure information (the size of each column), you can use sqlldr and specify the size of each column in the control file and sqlldr will load each column based on that.

This is how you need to write in your control file:
LOAD DATA
  INFILE filename.dat
  APPEND
  INTO TABLE coredata
  (
Column1    POSITION(1:12) CHAR,
Column2    POSITION(13:204) CHAR
)

Couple of things to remark:
position[start pont:end point]
I made the mistake to think that the second value was the length of the column, which is wrong is the end of the column which I do not like since it woukd be better to just give the start point and the length. You need to calculate that for each column. I know it is just adding all the time but still I would rather put the length instead of the end point.

infile:[filename.dat]
You can add multiple lines like this to import multiple files in one execution instead of changing the name for every file and execution.

For example, if you add:
OPTIONS (SKIP=1, LOAD=10, ERRORS=5)
at the beginning it will skip 1 row, load just 10 rows and limit to 5 errors.

Once you have that you only need to execute it using sqlldr like this:
sqlldr username/password loader=loader.ctl
Sqlldr is an amazing tool if you need to import huge amounts of data. I really recommend it. It has the best performance comparing other options and it supports tons of configurations like, importing multiple files at once, or import to a different tables, you can manipulate the data while it inserts, parallel processing, append or replace data, skip rows, limit the rows inserted. It is a huge list so you should really look into it.

Hope it helps someone, happy coding :)

Friday, May 6, 2011

Solution for ORA-01033 caused by ORA-01157 and ORA-01110

Today I was asked to do some work with some data. Basically I have to import the raw data into something more usable, easy to manipulate and run queries. My first option as usual was to use Oracle.

I started my server and listener and try to connect my SQL Developer. I like this front end because is easy to use and what's more it is supported by Oracle which makes the integration easier. Anyways, I tried to connect it and I couldn't so my next try was to use command line and use sqlplus which is the default command interaction you have when you install Oracle DB Server. I executed:
sqlplus <username>/<password>
and I got an ORA-01033: ORACLE initialization or shutdown in progress. I had this issue before and I just used to wait or even re-start my computer but this time it did not work so I had to try another things. I tried running:

C:\> sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Thu May 5 17:22:38 2011

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> startup;
ORA-01081: cannot start already-running ORACLE - shut it down first
SQL> alter database open;
alter database open
*
ERROR at line 1:
ORA-01157: cannot identify/lock data file 6 - see DBWR trace file
ORA-01110: data file 6: '\PATH\TO\FILE\CMS2.DAT'

This last command gave me the real reason it seems the server was looking for a DAT file that was no longer in the system which was true, I removed some files but it seems the Oracle DB server was still looking for them. So the solution was to tell the server to stop looking for these files. In order to do that I executed:

SQL> alter database datafile '\PATH\TO\FILE\CMS2.DAT' offline drop;
Database altered.

Now that the file has been deleted we restart the server:

SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.

Total System Global Area  778387456 bytes
Fixed Size                  1374808 bytes
Variable Size             385877416 bytes
Database Buffers          385875968 bytes
Redo Buffers                5259264 bytes
Database mounted.
Database opened.

And now everything should be working just fine. Oracle can give us errors when using it but sometimes they are not really the root cause of them this is something I hate about it. We need to be careful and find the real cause before start trying to solve the problem. In this case ORA-01033  was not the real issue, ORA-01157 and ORA-01110 were the root cause and usually because of these kind of issues we have to re-install or try crazy things when the solutions is something different, something simpler.

Hope this helps someone :)

Wednesday, November 22, 2006

A donde se dirigen todos estos Eventos

Cada día leo algunas páginas para actualizarme y saber como andan las cosas en el medio y cada vez me topo con cada noticia que me intriga y me lleva a la reflección. Este último mes, o meses diría yo hemos tenido unas noticias que intrigan a medio mundo. Estas noticias provienen de empresas grandes muy bien conocidas por todos como Oracle, Microsoft, Sun, RedHat y Novell.

Oracle se lanza contra Red Hat
 Bueno hace tiempo habían los rumores que Oracle pensaba sacar su própia distro y poes lo hizo, el 26 de octubre lanzó su "Unbreakable Linux" ("Linux irrompible"), y para niveles empresariales! y claro esta junto con su respectivo soporte y a menor precio!, en sí era el inicio de una pelea con Red Hat puesto que ellos hacen lo mismo y no tardo en mostrarse las consecuencias de esto, al poco tiempo las acciones de Red Hat cayeron increiblemente.
Se que es un golpe duro para Red Hat pero también veamos el lado objetivo de esto, el que Oracle, para mi la segunda empresa de software y que ademas es reconocida por el buen soporte que tiene a sus productos, ingrese en el mercado de servidores y con su propia distro y soporte, significa un gran impulso de GNU/Linux a nivel empresarial no creen? y bueno soñando un poco mas, un perjudicado a largo plazo sería Microsoft.

Microsoft y Novell 
 Esta noticia dejó impresionados a todos, incluso en las listas de discusión en las que estoy inscrito causo harto revuelo, mandaban links a las noticias de distintas páginas, que en escencia dicen lo mismo, pero no leí un comentario obejtivo de ellos o algo parecido.
Si no estoy mal esto aconteció a los pocos días de conocerse el anucio de Oracle. Microsoft y Novell hacen un acuerdo en el cual  hasta donde entendí Microsoft se vuelve en una especie de revendedor de SUSE Linux y además se compromete a no demandar a los usuarios de SUSE (y viceversa) por violaciones de patentes. Quisiera saber que patentes son esas.
En si Microsoft está amenazando a todos aquellos usuarios de Linux que no utilicen SUSE a ser demandados por violación de patente. La amenaza también alcanza a los productores de otras distribuciones, quienes para poder proteger a sus clientes, deberían firmar un convenio del mismo tenor con Microsoft. Deden estar locos!.

Lo que me confirmó esta noticia fue cuando Steve Ballmer (CEO de Microsoft)  sugirio posibles problemas legales para quienes usen otra distribución de GNU/Linux. Incluso este buen señor ha afirmado oficialmente: "Linux usa nuestra propiedad intelectual". Me intriga saber que le debe GNU/Linux a Microsoft en cuestion de patentes y propiedades intelectuales, si mas bien yo uso Linux porque no tiene nada que ver con Microsoft, como puede probar eso?.
Estas son algunas de las declaraciones de Ballmer, extraídas del link anterior (traducidas si hay error por favor decirme):
  • Linux "usa nuestra propiedad intelectual" y Microsoft quiere "obtener el retorno económico apropiado de nuestra innovación para nuestros accionistas".
  • "Novell nos paga dinero por el derecho de decirle a los clientes que cualquiera que use SUSE Linux está apropiadamente cubierto".
  • Esto "es importante para nosotros, porque creemos que cada usuario de Linux básicamente tiene una obligación oculta en su balance".
  • "Sólo los clientes que usan SUSE han pagado por la propiedad intelectual de Microsoft".
  • "Estamos dispuestos a hacer convenios con Red Hat y otros distribuidores de Linux". El trato con Novell "no es exclusivo".
No sé como ver esto, como un contraataque? mientras Oracle trata de impulsar el uso y el crecimiento de GNU/Linux ( aunque de dudosa forma a mi parecer )  ampliando sus productos y servicios especialmente, Microsoft intenta frenar este avance mediante amenazas y trabas legales. Ya no sé que pensar, se los dejo a uds :)
 De algo estoy seguro esta noticia causo algún resentimiento hacia aquellos que usan Suse eso si puedo asegurarlo, algo como "No usar más SUSE". Francamente nunca lo he utilizado como se debiera pero recibí buenos comentarios sobre esa distro. Pero eso si nada bueno puede resultar de una alianza con Microsoft.
Novell viendo todo esto sacó una carta abierta a la comunidad ( en inglés) donde aclara varias cosas y en sí dice a la comunidad que no se preocupe que todo lo que hacen es por el bien de Linux, que su principal meta es proteger, preservar y promover la libertad para el software libre y open source. Desmienten las afirmaciones hechas por Microsoft acerca de Linux y las patentes. Que el objetivo de este acuerdo es mejorar la interoperabilidad entre Linux y Windows, esto incluye nuevas tecnologías y estándares para la administración de servidores, compatibilidad de formatos de archivos y virtualización. También hace enfasis en que la comunidad Linux se beneficiará de la creación y publicación de código open source para mejorar la interoperabilidad de Linux con Windows, uds creen que se publique ese código? tengo mis dudas pero quien sabe.

Les dejo la lectura completa para dar sus criterios al respecto, pero yo sigo pensando que hacen mal, por mas de que quieran proteger y ayudar a la comunidad esa no es una forma correcta de hacerlo, lo digo por todas las cosas que en el pasado han ocurrido con Microsoft.

Java bajo licencia GPL
 Esta noticia ya venía desde hace tiempo, empezó como rumor ya que todos hablanban de eso menos Sun Microsystems, en fin. Java para mi 100pre tendrá un lugarcito y porque no debería si hasta donde se es lenguaje que encabeza la lista en medios empresariales. Siempre hubo presiones por parte de toda la comunidad de que se liberara este lenguaje tan popular.
Al fin el 23 de octubre creo yo Sun escuchó las plegarias y anunció que su tan popular lenguaje sería liberado . Esto causo grandes confusiones ya que todos andaban diciendo que ya fue liberado, cosa mas falsa no podía ser ya que lo se anunció es que se liberaría pero recien el 2007, fecha exacta creo que no confirmaron. Luego hace pocos días Sun dijo que sería bajo la licencia GPL, cosa que a todos nos pone con la cara de alegría :)
No quisera hablar mucho sobre las consecuencias que esto va a provocar o sus directas implicaciones, pero a grandes rasgos diria que la GPL seguiría afianzándose como una licencia válida en el mundo empresarial, algo que Microsoft ha tratado de evitar afirmando que la GPL es incompatible con los negocios). Y ni que decir de todo lo que la comunidad podría aportar a este lenguaje , yo creo que ahí Microsoft haría lo imposible frenar esto y supongo que su plataforma de desarrollo, Visual Studio sería la primera en ser afectada.

Resumiendo 
 Bueno francamente no sé a donde dirige toda esta serie de eventos, no sé si las compañias estan jugando con nostros y ver como reaccionamos a sus movidas. Todo esto tiene que llevar a algo, eso espero, por una parte parece que la comunidad va ganando terreno con lo de Oracle y Java pero por otra parte vemos como Microsoft sigue tratando de que ese terreno sea devuelto.
Parece como si estas grandes compañias nos vieran como titeres a quienes pueden manipular con sus "arreglos" , cambios de opinion etc etc, acaso nosotros nos debemos a ellos? es cierto, cada vez dependemos mas de sus tecnologías y todo lo que eso conlleva, pero hasta cuando tendremos que seguir sus reglas? hacen y deshacen cosas y los que tenemos que sufrir somos nosotros, es verdad que 100pre tenemos otra opción, ya sea Libre o Pago, pero a ratos pareciera que las cosas van en rumbo en la cada vez el futuro es incierto para los que dependemos de sus tecnologías. O tal vez estoy delirando un poco pero de alguna forma había que decirlo.


Críticas, Opiniones, Aportes, Correcciones y demas son bienvenidas.
salu2.