Página 1 de 1

Conexión con SQL Server

NotaPublicado: 2016-03-23 15:50 @701
por BigBear
Hola. Estoy tratando de conectarme a SQL Server 2005 desde Perl. Ya lo hice con C# y Java con el mismo servidor. Quería hacerlo en Perl. Tengo el siguiente código:

Primer intento.
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!usr/bin/perl
  2. use DBI;
  3.  
  4. my $data_source = q/dbi:ODBC:localhost\SQLEXPRESS/;
  5. my $user = q/admin/;
  6. my $password = q/123456/;
  7.  
  8. my $dbh = DBI->connect($data_source, $user, $password)
  9.     or die "Can't connect to $data_source: $DBI::errstr";
Coloreado en 0.006 segundos, usando GeSHi 1.0.8.4

Salida:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
DBI connect('localhost','admin',...) failed: [Microsoft][Administrador de controladores ODBC] No se encuentra el nombre del origen de datos y no se especificó ningún controlador predeterminado (SQL-IM002) at C:\Users\Doddy\Desktop\test\conexion.pl line 14.
Can't connect to dbi:ODBC:localhost: [Microsoft][Administrador de controladores ODBC] No se encuentra el nombre del origen de datos y no se especificó ningún controlador predeterminado (SQL-IM002) at C:\Users\Doddy\test\conexion.pl line 14.
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Segundo intento:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!usr/bin/perl
  2. use DBI;
  3.  
  4. my $user = "admin";
  5. my $password = "123456";
  6.  
  7. my $dbh =  DBI->connect("dbi:ODBC:Driver={SQL Server};Server=localhost\SQLEXPRESS;UID=$user;PWD=$password") or die "Can't connect to $data_source: $DBI::errstr";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Salida:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
DBI connect('Driver={SQL Server};Server=localhostSQLEXPRESS;UID=admin;PWD=123456','',...) failed: [Microsoft][ODBC SQL Server Driver][DBNETLIB]No existe el servidor SQL Server o se ha denegado el acceso al mismo. (SQL-08001) [state was 08001 now 01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000) at C:\Users\Doddy\Desktop\Mis Programas\Programas de la facultad\Perl\conexion.pl line 9.
Can't connect to : [Microsoft][ODBC SQL Server Driver][DBNETLIB]No existe el servidor SQL Server o se ha denegado el acceso al mismo. (SQL-08001) [state was 08001 now 01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000) at C:\Users\Doddy\Desktop\test\conexion.pl line 9.
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


La cadena de conexión que uso en Delphi: Provider=SQLOLEDB.1;Persist Security Info=False;User ID=admin;Password=123456;Initial Catalog=sistema;Data Source=localhost\SQLEXPRESS';

¿ Cómo puedo conectarme ?

Re: Conexión con SQL Server

NotaPublicado: 2016-03-23 16:31 @729
por explorer
Podría ser que la DSN esté mal definida, pero yo la veo bien.

Por otra parte, si te conectas con ODBC, ¿tienes definida una fuente de datos en el Panel de control de ODBC? Sin esto, no te funcionará. Bueno, sí que se puede, pero depende de la versión de MSSQL que vayas a usar (con las últimas versiones, no).

En la página de Easysoft hay manuales con ejemplos y guías de cómo hacerlo.

Si estás usando ActivePerl, deberías consultar sus foros, donde hay más ejemplos. Ahí, por ejemplo, se resolvió simplemente cambiando la '\' por un '\\', en el DSN (último mensaje de la página). Si ese es el caso, cambia "localhost\SQLEXPRESS" por "localhost\\SQLEXPRESS".

Re: Conexión con SQL Server

NotaPublicado: 2016-04-04 19:31 @855
por BigBear
Sí, era eso. Gracias, explorer.

Tengo esta función:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. sub cargarConsulta {
  2.        
  3.         my $cantidad = "0";
  4.         my @rows = ();
  5.         my $sql = "select * from usuarios";
  6.         my $sth = $conexion->prepare($sql) or die("\n\nPREPARE ERROR:\n\n$DBI::errstr");
  7.        
  8.         $sth->execute or die("\n\nQUERY ERROR:\n\n$DBI::errstr");
  9.  
  10.         while(@rows = $sth->fetchrow_array()) {
  11.                 $cantidad++;
  12.         }
  13.        
  14.         return $cantidad; # return true ?
  15.  
  16. }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Quería preguntarte cómo comprobar que toda la consulta salió bien. Eso se resuelve retornando a la función true o false con try y catch en Java, pero, en Perl, ¿cómo lo resolvería?

Re: Conexión con SQL Server

NotaPublicado: 2016-04-05 03:00 @167
por explorer
La captura de excepciones se suele hacer con eval(), pero es más cómo usar Try::Tiny.