Connecting to SQL Server using Perl using DBI? - sql

I am trying to connect to SQL server using Perl DBI module, I have tried all the connection string format still Perl is throwing invalid connection string error.
I have already tried code snippet available on perl monk website.
#!/usr/bin/perl -w
use strict;
use DBI;
# Set up variables for the connection
my $server_name = '00.120.124.1;3181';
my $database_name = 'abcd';
my $database_user = 'kkkk';
my $database_pass = 'password';
my $DSN = 'driver={SQL Server};server=$server_name;da
+tabase=$database_name;uid=$database_user;pwd=$database_pass;';
my $dbh = DBI->connect("DBI:ODBC:$DSN") || die "Couldn't open database
+: $DBI::errstr\n";
Expected result is to connect to Database.
failed: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000) [state was 01000 now 01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (SQL-01S00) at perl.pl line 16. Couldn't open database +: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (SQL-08001) [state was 08001 now 01000] Invalid connection string attribute (SQL-01S00)

The lines of your post that begin with +
+tabase=$database_name;uid=$database_user;pwd=$database_pass;';
+: $DBI::errstr\n";
were incorrectly copied and pasted from perlmonks.org. The leading + sign is a convention that indicates a long line was split. You should delete the + and join the line to the previous line, so that your code will read
my $DSN = 'driver={SQL Server};server=$server_name;database=$database_name;uid=$database_user;pwd=$database_pass;';
my $dbh = DBI->connect("DBI:ODBC:$DSN") || die "Couldn't open database: $DBI::errstr\n";

Your error message contains the following:
SQL Server does not exist or access denied
Your set-up code contains the following:
my $server_name = '00.120.124.1;3181';
'00.120.124.1;3181' is not a valid server name or IP address. You should correct the IP address section (it can't start with '00') and remove the port into a separate parameter.
You also have the username and password as part of your DSN. I don't know if DBD::ODBC supports that usage (it's not mentioned in the documentation) but it's more traditional to have those as separate parameters to the connect() call.
All in all, I think you want something more like this:
my $server_name = '00.120.124.1'; # But this needs to be corrected
my $server_port = 3181;
my $database_name = 'abcd';
my $database_user = 'kkkk';
my $database_pass = 'password';
my $DSN = "driver={SQL Server};server=$server_name;port=$server_port;database=$database_name";
my $dbh = DBI->connect("DBI:ODBC:$DSN", $database_user, $database_pass)
|| die "Couldn't open database: $DBI::errstr\n";
Also note that I've changed the quote characters used to create your $DSN variable from single quotes to double quotes. Variables are not expanded in signel quotes, so you weren't getting the values of $server_name, etc. in your DSN.

The better way to connect is with the DBD::Sybase module. The name wouldn't suggest it but SQL Server takes its lineage from Sybase. That way you can avoid ODBC. http://metacpan.org/pod/DBD::Sybase#Using-DBD::Sybase-with-MS-SQL

Related

Unable to execute SQL script in Perl

I'm trying to execute SQL script that has lot of DML commands using Perl.
Basically there is some reference number which is required to be updated every time in SQL script before it executes, so I'm passing it as a parameter to Perl script which will further replace with parameter and execute. I'm doing this task in IntelliJ IDEA 2022.3.1 (Community Edition).
Problem: Unable to understand but Database connectivity is completely fine, and is fetching SQL script correctly, even replacement of reference number is also fine. But when trying to execute, it's not doing any changes in the Database. It looks like SQL commands are not really executing (as it is executing quickly which is not supposed to). I added warn with execute, so I got that warn message, but there is no error/exception message.
Please try to understand more details via code.
If anywhere I'm doing it wrong, please tell me. I have basic knowledge of Perl so might be doing it wrong. Can't provide more details about SQL script, it is confidential. But I can make sure that there is no error, as it is working fine if execute in it's dedicated tool. Thank you in advance!
#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
use DBI;
# Connect to the database
my $EnvDatabase = $ENV{"DATABASE"};
if (! defined $EnvDatabase) {
&ERROR ("The environment variable DATABASE is not defined");
exit (-1);
}
print "Updating in Database: $EnvDatabase\n" ;
my ($DBUser, $DBPass, $SID) = split (/\/|\#/,$EnvDatabase);
if (! (defined $DBUser && defined $DBPass && defined $SID )) {
&ERROR ('The environment variable DATABASE is not properly defined');
exit (-1);
}
my $dbh = DBI->connect( "dbi:Oracle:".$SID, $DBUser, $DBPass,{AutoCommit=>0,PrintError=>0})
|| &errorExit( "Unable to connect to database [$DBI::errstr] ");
# Get the input parameters
my $param1 = shift;
my $param2 = "###123###";
# Read the SQL file into a variable
my $sql = do {
local $/ = undef;
open my $fh, "<", "C:/someScript/someSampleSqlWithDMLCommands.sql" or die "could not open file: $!";
<$fh>;
};
# Replace with the parameter
$sql =~ s/$param2/$param1/g;
# Execute the SQL statements
$dbh->do($sql) || warn("Unable to execute ", $dbh->errstr);
$dbh->commit;
$dbh->disconnect;
OUTPUT: Updating in Database: database name declared in environment
Unable to execute ORA-00900: invalid SQL statement (DBD ERROR: OCIStmtExecute) at C:/**/autoScript.pl line 37.
Process finished with exit code 0

Token unknown in SQLCODE

CREATE DATABASE test.fdb -user ZZZZZ -password *******;
I am using above command to create a database for my project in windows 7. I am new to Firebird SQL, I used my system credentials for log in but it is showing some error. So, How can I reset my password?
SQL error code = -104
Token unknown.
I don't even know the significance of SQLCODE = -104.
The error shown is not caused by not knowing the database password, you have a syntax error in the CREATE DATABASE statement. The error Token unknown means that the statement parser read something it didn't expect; the error is usually followed by the offending token.
If I execute your statement using ISQL on Firebird 3.0, I get the following full error:
SQL> CREATE DATABASE test.fdb -user SYSDBA -password *******;
Statement failed, SQLSTATE = 42000
SQL error code = -104
-Token unknown
-test
Which means that at (or before) test something in your query is wrong.
The right syntax for CREATE DATABASE is:
CREATE {DATABASE | SCHEMA} '<filespec>'
[USER 'username' [PASSWORD 'password']]
[PAGE_SIZE [=] size]
[LENGTH [=] num [PAGE[S]]
[SET NAMES 'charset']
[DEFAULT CHARACTER SET default_charset
[COLLATION collation]] -- not supported in ESQL
[<sec_file> [<sec_file> ...]]
[DIFFERENCE FILE 'diff_file']; -- not supported in ESQL
<filespec> ::= [<server_spec>]{filepath | db_alias}
<server_spec> ::= servername [/{port|service}]: | \\servername\
<sec_file> ::= FILE 'filepath'
[LENGTH [=] num [PAGE[S]] [STARTING [AT [PAGE]] pagenum]
In other words your statement should be:
create database 'test.fdb' user SYSDBA password '*******';
So:
Quotes around the path to the database file (or alias)
No - before the user and password clause
Quotes around the password (contrary to the syntax shown, quotes are optional around the user name)
As an aside, the SQL error code is usually not very interesting (as some of them can cover several different errors).

Running db2 from bash script not working?

I'm currently using bash on CentOS. DB2 is installed and db2 is on my path.
I have a few lines in a script which are supposed to update my db2 database, but they aren't working. As a minimal reproduction, I can do the exact same thing right in the bash command line and get the same error. Here's that reproduction:
$ db2 connect to PLT02345 user uni using uni; db2 update USM_USER set STATUS = 1 where NAME = 'asm_admin'
I expect this to set STATUS to 1 for everything in PLT02345.USM_USER where the NAME is currently asm_admin.
Instead, I get an error about "ASM_ADMIN" not being valid in the context where it's used. Here's the full output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.2
SQL authorization ID = UNI
Local database alias = PLT02345
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0206N "ASM_ADMIN" is not valid in the context where it is used.
SQLSTATE=42703
I'm confused - what about this makes it not valid? Is bash somehow mutilating the command and not passing everything as it should to db2?
If you're running this from the command line, Bash will drop the 's off 'asm_admin' because it simply assumes you're passing a string. The end result is the SQL becoming WHERE name = asm_admin which is invalid.
To correct this, you need to quote your whole command:
db2 "update USM_USER set STATUS = 1 where NAME = 'asm_admin'"

ORA-00900: invalid SQL statement

i have sql file that i am trying to execute from a perl script like that-
connect to DB
my $dsn = "dbi:Oracle:$ENV{MPR_DB_INSTANCE}";
my $tg_dbh = DBI->connect($dsn,$ENV{MPR_DB_USER},$ENV{MPR_DB_PASS},{AutoCommit=>0});
unless ($tg_dbh) {&PrintAndLog("\nDBI connect failed: Unable to connect to database $tg_dbh");}
print("\nConnected to DB: $ENV{MPR_DB_USER}\#$ENV{MPR_DB_INSTANCE}\n");
print("\nRunning SQL for SY Test\n");
$sql_statement = $tg_dbh->prepare("$ENV{BIN_PATH}/SY_TG_Test.sql");
$sql_statement->execute();
$tg_dbh->commit;
I am getting ORA-00900: invalid SQL statement execute.
any idea what am i doing wrong?
The argument to the prepare method should be an SQL statement (with placeholders), not a file name.
open my $SQL, '<', "$ENV{BIN_PATH}/SY_TG_Test.sql" or die $!;
my $sql_statement = $tg_dbh->prepare(do {local $/; <$SQL>});

Can connect with PERL but can't query MSSQL 2k8 database

I am able to connect to my MSSQL server but getting a permission error when trying
to query the database. I see the "YAY" in the script below, but get this error:
*[Microsoft][ODBC SQL Server Driver][SQL Server]The SELECT permission was denied on the object 'TICKET_TYPES', database 'DBNAME', schema 'dbo'. (SQL-42000)(DBD: st_execute/SQLExecute err=-1)*
If I add "DOMAIN\DOMAIN Users" with DBO access it works, but when I take that away it doesn't. I think it's connecting to the database as the logon user, not the SQL user that is set up in the connect string but not positive.
The SQL Driver is set to use "With SQL Server Authentication using a login ID..." and not "Windows NT..."
Classic ASP connects and queries fine. I can access/query the DB using the SQL account in the connect string via ASP classic and SQL Server Management Studio.
It may be relevant that it also works perfectly against SQL2005 but not SQL2008 which we are trying to upgrade to. Everything is fine with our upgrade except our couple Perl scripts just don't get into the tables.
use lib "cgi-bin";
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
require "Babel.pm";
my $y = new Babel;
my $q = new CGI;
$SERVER_N = $q->server_name() ;
### CONNECT
$database = "DBNAME";
$dbusername = "SQLUSERNAME";
$dbpassword = "SQLUSERPASSWORD";
$server="SQLSERVERIP";
print "Content-type: text/html\n\n";
$dbh = DBI-> connect( "DBI:ODBC:driver={SQL Server};
Server=$server;
Database=$database;
UID=$dbusername;
PWD=$dbpassword") || die &DBerror;
if ($DBI::errstr) {print "Error: Connecting to the Database!";
exit;}else{
print "YAY! <br><br>";
}
### END: CONNECT
$v2SQL = "select distinct ROUTE from TICKET_TYPES";
$css1 = $dbh->prepare ($v2SQL);
$css1->execute () || print $css1->errstr;
while ((#row) = $css1 ->fetchrow_array) {
$MANA = #row[0];
print "$MANA";
}
$css1->finish () || print $css1->errstr;