Habilitando MySQL para Rails

julho 19, 2010
If at any point when you’ve upgraded to Rails 2.2. you get the following error on Windows:

“!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.”

the problem is because MySQL 5.1 client library doesn’t play well with Rails – the solution is simple however:

– download older MySQL client library, for example one from InstantRails: http://instantrails.rubyforge.org/svn/t … bmySQL.dll

– copy the downloaded file to C:\Ruby\bin (or wherever you installed Ruby)

– restart MySQL server

That’s it! Just thought I’d share this with others, lost me an hour of researching.

Good luck!

Instalar MySQL JDBC ActiveRecord adapter

gem install activerecord-jdbcmysql-adapter

Alterar arquivo de configuraçao \config\database.yml

adapter: jdbcmysql

Corrigindo erro SQL Server 2005 Express – Atachando databases (.mdf)

junho 12, 2007

Quando tenta atachar um .mdf ao Server dá erro 5 (access denied).

“Unable to open the physical file ‘c:\Program Files\Microsoft SQL Server\MSSQL1.1\MSSQL\Data\TravCom.mdf’. Operating system error 5 (Access Denied).”

Now to resolve this you need not to uninstall Sql Express. Just go to SQL express configuration manager and click on Services from the left pane. From the right pane select Sql server service and go to its properties. The builtin login should be “Nerwork Service”, change it to “Local system” and restart the service. thats it.


Excluindo o boot

junho 11, 2007
clipped from www.pcforum.com.br

Instalou o Vista junto com o XP e agora quer desinstalar?
Apenas formatando a partio com o Vista no ir resolver,pois o boot do computador est sendo comandado pelo Windows Vista.
Antes de formatar a partio ,insira o DVD de instalao do Windows Vista e execute o comando abaixo(iniciar / executar):

d:\boot\bootsect.exe /nt52 ALL /force (d: a unidade de DVD onde est a instalao do Vista).

Depois de executar o comando, delete os arquivos boot.bak e bootsect.bak no seu HD ,nq partio onde est instalado o Windows XP.

Reinicie o computador.

Agora pode formatar a partio como Vista que o dual boot j era.


fonte: asmon

ah … ok, um bom pormenor que nao e preciso eskecer
  blog it

JDBC to SQL Server Express

junho 5, 2007

JDBC to SQL Server Express

Connecting JDBC-based tools such as SQL Developer or DbVisualizer to SQL Server Express required the following steps:

  • Obtain JDBC Driver
  • TCP/IP for SQL Server Express
  • Authentication Method

Obtain JDBC Driver

Using SQL Developer, when you get the following exception …

Unable to find driver: net.sourceforge.jtds.jdbc.Driver

… download the jTDS JDBC driver and install it in your JRE‘s ext folder. The latest version of the driver is 1.2. Of course, there are other JDBC drivers for SQL Server you can use.

TCP/IP for SQL Server Express

By default, TCP/IP for SQL Server Express is disabled, so JDBC cannot connect to it and you may get the following exception …

Network error IOException: Connection refused: connect

Enable TCP/IP

To enable TCP/IP, start SQL Server Configuration Manager.

  1. Expand SQL Server 2005 Network Configuration node.
  2. In the right pane, select Protocols for SQLEXPRESS. The right pane should now show Protocols and Status columns.
  3. Select Enable from the TCP/IP context menu.

Find or Configure TCP/IP Port

After enabling TCP/IP, you have to find out which port number to use. SQL Server Express allocates a port dynamically each time it is started, so to find or configure the port number, continue using SQL Server Configuration Manager

  1. Select Properties from the TCP/IP context menu. The TCP/IP Properties dialog should open.
  2. Select the IP Addresses tab.
  3. In the IPA3 ( node …
    1. The TCP Dynamic Ports field shows the currently used port number. If you set that field to blank, then SQL Server Express should not automatically choose another port when it restarts.
    2. Set the desired port number in the TCP Port field (1433).
    3. Press OK to apply your settings and close the dialog.


If you change the TCP/IP port, you have to restart SQL Server Express before it can use the new port number. To test that your port number is used, start a cmd window and type: netstat -an. For instance, if you used port 1433, you should see this line in the list of ports used:

TCP               LISTENING

Authentication Method

By default, SQL Server Express uses Windows Authentication Mode to authenticate connections. If you get this exception …

Login failed for user '<User name>'. The user is not associated with a trusted SQL Server connection.

… then you may have to enable SQL Server Authentication Mode and create or enable a user.

  1. Start Microsoft SQL Server Management Studio Express (SSMSE) and connect to your database server.
  2. In Object Explorer pane, select Properties from your database’s context menu. The Server Properties dialog should open.
  3. Select Security page.
  4. Select SQL Server and Windows Authentication Mode check box.
  5. Press OK button to close the dialog.
  6. In Object Explorer pane, expand Security / Logins node.
  7. Select existing user sa. Note that there is a red downward arrow next to that user’s image.
  8. View sa‘s properties. The Login Properties dialog should open.
  9. Select Status page.
  10. Ensure that the Login: Enabled radio button is selected.
  11. Select General page.
  12. Enter a password for this user.
  13. Press OK button to close the dialog.
  14. If you refresh the Object Explorer pane, note that user sa no longer has a red downward arrow.

Finally …

After all these steps, you should be able to connect to your SQL Server Express database using JDBC.

SSMSE console

The long version.

This entry is designed to help explain the reasons behind the steps in the short version of this post. Lets walk through the steps and the problems and try and explain whats happening

Checking to make sure that Express is running via SQLCMD

The default install for SQL Express installs Express as a named instance(called SQLExpress), with no network listening and with Windows Authentication support only.

To connect to a named instance of SQL Server the convention is to use a servername of the format <servername>\<instancename>, its also possible to shortcut the machinename to either “.” or “(local)”(these shortcuts work with all protocols, localhost will also work but only with TCP/IP in older clients,however SQL Native Access supports resolution of LocalHost for Named Pipes and Shared Memory).

No user id and password has been specified because of the default windows authentication, if the install had been changed to specify mixed mode authentication and a password had been given then this could have been used.

Enabling Protocols

Because SQL Server Express does not listen on the network by default connections are made using a local protocol, in the case of the VS 2005 SKUs this is the shared memory protocol. The interface to this has changed in SQL Server 2005 such that older clients can no longer use it. Hence for older clients to work a different local protocol or a network protocol must be used, these are not enabled by default and must be manually enabled.

SQL Browser Service

In general when a client connects remotely to a SQL Server named instance the client does not know the port that the instance is listening on(you can work around this by configuring SQL Server named instances to listen on a specific port and then specifying that port in the connection string in the format <servername>,<port number>)

So when an application attempts to connect to a named instance in the form <servername>\<instancename> the client connection needs to be directed to the correct port. In SQL Server 2000 one of the running services had a built in listener that received the named instance connection requests and redirected them appropriately.

In SQL Server 2005 this functionality has been moved to a dedicated listener service, that service is SQLBrowser.

SQLBrowser also performs another service, that of SQL Server Discovery, its common in many UIs from Microsoft and others to have the ability to browse for instances of SQL Server running locally or remotely, again in SQL Server 2000 this was handled by one of the running instances of SQL Server, in SQL Server 2005 this is handled by the SQLBrowser Service.

Thus the SQLBrowser Service must be started to be able to discover any instance on the machine, and also to connect to named instances through protocols other than shared memory. If network protocols are not enabled via the setup switch then the browser service is not set to autostart.

SQL Native Client

SQL Server native connectivity is defined as connectivity through OLE DB(ADO uses OLE DB under the covers) or ODBC means in SQL Server 2005 (dblib is not an included as a data access technology in SQL Server 2005).

In previous releases of SQL Server(SQL7 and SQL2000) an update to MDAC was preferred for client apps, this means the installation of an entire MDAC update for SQL Server connectivity. In SQL Server 2005 we no longer require an MDAC update as we have refactored out the SQL Server specific connectivity components for OLE DB and ODBC.

As such in SQL Server 2005 no MDAC update is required to connect(although MDAC 2.8 is preferred, any MDAC from Windows 2000 SP3 upwards is supported), but a new component is required. This component is referred to as SQL Native Access.

These components include support for OLE DB and ODBC accessed through a single .dll called: SQLNCLI.dll, this file and its support files are redistributable.

SQL Native Client is NOT required for managed data access via .Net APIs.

-Euan Garden

Product Unit Manager

SQL Server Tools

Connection URL JDBC MICROSOFT: jdbc:sqlserver://localhost\SQLEXPRESS;databaseName=teste

Connection URL JDBC JTDS : jdbc:jtds:sqlserver://localhost:1433/TESTE;instance=SQLEXPRESS

Arquitetura de Aplicação

maio 28, 2007

– camada UI(User Interface): Nesta camada vc implementa a interface com usuário. Ex: formulario Cliente, formulario Contas, etc…

– camada de comunicação: Aqui, é implementado a comunicação com as outras camadas do sistema. Por exemplo vc pode definir um ValueObject( objeto genérico que conterá os dados da interface gráfica) que será utilizado pela camada de acesso aos dados. o Value Object pode ser uma interface e pode ser definido uma implementação para cada formulario q vc tenha.

– camada de negocios Nesta camada vc implementa os objetos que encapsularão os dados que serão persistentes(gravados/recuperados do BD). Ex: Cliente, Conta.

– Camada de Acesso aos dados: nesta camada vc implementa os DAOs, que tem a resposabilidade de se comunicar com o banco de dados, através das ‘querys’. Ex: DaoCliente, DaoConta, etc…

Na epoca estavam discutindo que a MVC implementa 1 camada (e não 3….). Eu entendi o conceito (camada de apresentação=MVC) mas como os padrões mudam e hoje existe camada pra tudo queria saber como isso está hoje??… eu li muito sobre o assunto e minha opinião é mais o menos o que essa figura diz…

– Camadas == Layers
O padrão que descreve a separação do sistema em camadas é o Layers, publicado em [Busch98] (referências no final). Este padrão mostra uma divisão do sistema em camadas, onde idealmente uma camada conhece e acessa apenas a camada imediatamente inferior, ou no máximo as camadas adjacentes.

– MVC = Model-View-Controller
Padrão usado na implementação do toolkit gráfico do Smalltalk. Uma descrição pode ser encontrada aqui.

Eu acredito que a confusão existe por causa da correspondência numérica que muitas vezes ocorre entre os padrões: MVC e Apresentação/Negócio/Persistência. Então, muitos acham que é a mesma coisa, o que não é verdade.

O padrão MVC, como implementado no Swing, funciona da seguinte maneira:
O componente recebe o input do usuário, interpertando-as; este componente envia ao modelo as alterações causadas pelo input; se o modelo for alterado, este envia uma notificação às views (que também são componentes), que por sua vez solicitam ao modelo os novos dados, para que possam se atualizar. Aqui pode se notar um triângulo, Controlador -> Modelo -> Visualização -> Controlador. Assim, o conceito de separação em camadas não é válido, pois a vizualização acessa diretamente o modelo (isto é, não existe a separação estrita em camadas).

Idealmente, acredito que o MVC faz parte da camada de apresentação (como era no conceito original), e não como divisor de camadas (o que deturpa o conceito de MVC e confunde a separação correta em camadas).

A minha concepção ainda é semelhante (MVC é parte da camada de apresentação), embora o modelo, como dito na discussão, pode ter conceitos distintos.
Acho que o seu diagrama simplifica um pouco o paradigma de arquitetura, e assim sendo, deveria distribuir melhor os componentes de negócio.

Um exemplo é que um web service não concentra suas atividades no modelo de negócio.
É mais uma interface de comunicação com outros sistemas e portanto, faria parte de uma camada chamada “integração”.
O mesmo se daria com códigos como RMI, ou CORBA por exemplo.
DAO’s fariam parte da camada de persistência.
Session Beans fariam parte da camada de negócio, assim como os DTO’s (que fariam parte do Model do MVC).
Porém, Entity Beans fazem parte da camada de persistência. Assim como outras alternativas como LDAP.


Arquitetura de sistemas muitas vezes é semelhante a um jogo de xadrez: possui certo nível de subjetividade e muitas vezes, um mesmo problema pode ter diversas soluções com arquiteturas bem distintas e igualmente eficazes. 

Gerando JPA com myEclipse

maio 27, 2007

1. Myeclipse JPA Tutorial.

Precisei alterar o código gerado para incluir o controle de transação para efetivamente ocorrer as atualizações no BD.

public void save(Counselors transientInstance) {
EntityManagerHelper.log(“saving Counselors instance”, Level.INFO, null);
try {

EntityManagerHelper.log(“save successful”, Level.INFO, null);
} catch (RuntimeException re) {
EntityManagerHelper.log(“save failed”, Level.SEVERE, re);
throw re;

public void delete(Counselors persistentInstance) {
EntityManagerHelper.log(“deleting Counselors instance”, Level.INFO,
try {
EntityManagerHelper.log(“delete successful”, Level.INFO, null);
} catch (RuntimeException re) {
EntityManagerHelper.log(“delete failed”, Level.SEVERE, re);
throw re;

public Counselors update(Counselors detachedInstance) {
EntityManagerHelper.log(“updating Counselors instance”, Level.INFO,
try {
Counselors result = getEntityManager().merge(detachedInstance);
EntityManagerHelper.log(“update successful”, Level.INFO, null);
return result;
} catch (RuntimeException re) {
EntityManagerHelper.log(“update failed”, Level.SEVERE, re);
throw re;


maio 19, 2007