Question

Using Perl DBI Connecting To MS-SQL

Asked by: billfinkri

What's wrong with my "DBI" code? I can NOT connect to the SQL server.

If you find my mistake, PLEASE be specific as possible with the syntax, please? (Even down to if I'm using the curley brackets correctly or not.)

I've been using DBI::Oracle for 2 years now, and have never seen a problem - but I just can't seem to use DBI to connect to the SQL server.

Thanks In Advance!

# Normal Perl Intro, /perl/bin/perl stuff goes here.
#
#

# Let The Users Know There Was A Problem
my $Error_Message = "\nThere Was A Problem Connecting To The Database\n";

my $q = new CGI;
use CGI;
# The Below Line - Takes Care Of Letting The User Know There Was An Error In The Web-Page!
use CGI::Carp (fatalsToBrowser);
use DBI;
# The Below Line Is Not Needed, Correct?
# use DBD::ODBC;
#

# print $q->header;

$dbusername = 'domain\user.name';
$dbpassword = 'password_here';
$server     = 'server_name_here';
$database   = 'Northwind';


$dbh = DBI->connect("DBI:ODBC:driver={SQL Server};Server=$server;Database=$database;UID=$dbusername;PWD=$dbpassword") ||  die "$Error_Message $DBI::errstr";

die $DBI::errstr if ($DBI::errstr);

$sql_statement = ('select * from northwind.employees');

$statementHandle = $dbh->prepare($sql_statement);
$statementHandle->execute()||die $statementHandle->errstr;

while (($cat1) = $statementHandle->fetchrow_array )
{
     print $cat1."\n";
 }

$statementHandle->disconnect();


====================
Here Are My Errors Reported
====================

[Fri Oct 28 13:18:24 2005] test_mssql.cgi:
[Fri Oct 28 13:18:24 2005] test_mssql.cgi: There Was A Problem Connecting To The Database
[Fri Oct 28 13:18:24 2005] test_mssql.cgi:  [Microsoft][ODBC SQL Server Driver]Client unable to establish connection (SQL-08001)
[Fri Oct 28 13:18:24 2005] test_mssql.cgi: [Microsoft][ODBC SQL Server Driver][Named Pipes]ConnectionOpen (CreateFile()). (SQL-01000
)(DBD: db_login/SQLConnect err=-1) at test_mssql.cgi line 54.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-10-28 at 10:15:05ID21611876
Tags

perl

,

dbi

,

sql

,

connect

Topic

Miscellaneous Programming

Participating Experts
2
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. cgi with perl or other lang
    which is the best in creating the CGI is it using perl or other language such as delphi, V c++,and etc
  2. Perl DBI
    I am trying to retrieve data from an Access database. When I use joins in the SQL Query absolutely no data is retrieved. Please can anyone tell me as how joins work while using the Perl DBI module ? Thanks
  3. Connecting to Oracle with DBI using DBD::ODBC
    I set up a system dsn on windows 2000 called Module_Ack. I am trying to connect via ODBC to an Oracle 8i database that is on another server on the network. My connect statement is the following: use DBI; $dbh = DBI->connect('dbi:ODBC:Module_Ack', 'username', 'password')...
  4. Perl DBI
    I'm new to Perl. I'm trying to execute an SQL UPDATE statement . The query is UPDATE CONTACTS SET ( LNAME= 'Doe', FNAME= 'John', TITLE= 'Manager', TEAM= 'Finance', OFFICE= 'XXX-XXX-XXXX', CELL= '', HOME= '', PAGER= '', LOCATION= 'Texas', MAILSTOP= 'XX-XXX' ) WHERE LNAME = ...
  5. connecting to MsSQL via Perl w/DBI::ODBC & iODBC
    Ok I'm trying to connect to a MS SQL database using perl with dbi and iODBC I installed DBI::ODBC I installed iODBC and I edited my odbc.ini file so it looks like this: [ODBC] Driver=/path/to/my/lib/libiodbc.so.2.1.8 UseCursorLib=0 [ODBC Data Sources] SQLServer_Ape_Test=Da...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: punkpulsePosted on 2005-10-28 at 10:41:27ID: 15181096

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/trblsql/tr_err_odbc_5stz.asp

01000 is "general warning" -- your connection was successful.  your problem is that you are checking for the existance of DBI->errstr rather than the defined value of $dbh.  you should never try to check for an error condition setting unless the function has failed.  since you never check the value of the DBI::connect call, your logic is flawed.

 

by: punkpulsePosted on 2005-10-28 at 10:46:22ID: 15181143

also, i'm not sure, but i think your DSN syntax is wrong.  try this:

my $dbh = DBI->connect("dbi:ODBC:driver={SQL Server};server=$server;database=$database", $dbusername, $dbpassword) or die "could not connect: " . DBI->errstr;

case DOES make a difference.  for instance, trying to use the "pg" postgres driver will fail.  but if you use the "Pg" postgres driver, it succeeds.

 

by: billfinkriPosted on 2005-10-28 at 10:46:57ID: 15181146

Soooo...what does this mean? (Please?)

I'm afraid that I'm not familiar with this sort of syntax.

Then what/where should I change the code?

Thanks!

 

by: punkpulsePosted on 2005-10-28 at 11:14:11ID: 15181396

i just showed you the code!  replace the DBI->connect line that you have with the one i just gave you.  if you "have been using DBI::Oracle for 2 years now", you shouldn't have to ask me that question.

that syntax is the de facto DBI syntax.  read the manual for DBI.

 

by: billfinkriPosted on 2005-10-28 at 11:34:50ID: 15181554

Thanks for "your code" ... I cut/pasted your line of code directly from EE here, and received the same error. (I don't think it IS connecting.)

If my syntax is (now) correct with your connect "code" - then I'm probably looking in the wrong place.

RE: Read CPAN's DBI manual?

Thanks for your troubles ... that's exactly where my other browser window is opened to as I type this response.

For what it's worth - one of the reasons to use (and pay for) EE is getting answers quickly and to have other programmers maybe shed some light on a missing comma or semicolon someplace.

Thus your suggestion to "Read The Manual For DBI", while a good suggestion, negates the purpose of EE. EE is just a quick way of getting what the boss would like done ASAP.

Truly withOUT sounding like I didn't appreciate your time - maybe a bit of patience on your tone in your responses is in line. (Then again, maybe you're having just as good a day as I am.)

 

by: punkpulsePosted on 2005-10-28 at 12:19:05ID: 15181924

well, perhaps your server isn't using named pipes for connecting.  have you tried using TCP/IP?

hrm, here's a snippet that says to do just that:

Why do I get "[Microsoft][ODBC SQL Server Driver][Named Pipes]ConnectionOpen (CreateFile())"

It is a resource issue when running a lot of processes (e.g. MultiProcess in the OOB Server) to the MS SQL Server ODBC driver issue. Switch to TCP/IP instead of named pipes in the MS SQL Server ODBC DSN and the problem will go away.

 

by: FishMongerPosted on 2005-10-29 at 09:17:38ID: 15185451

I see a number of issues that need to be addressed.

1) You're not using the strict pragma and you probably haven't enabled warnings.
2) You're creating your cgi object before the importing the CGI module.
3) You commented out the line that prints the html header, so it's unclear if this is or is not a cgi script.
4) Is the name of your database 'Northwind' or 'northwind'?  Case matters when connecting.
5) Your select statement implies that you're retrieving multiple fields, but your while loop is only using 1 field.
6) You're performing the disconnect on the statement handle instead of the database handle.

See if this version works better.

#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
use DBI;

my ($dbh, $sth);
my $Error_Message = "\nThere Was A Problem Connecting To The Database\n";
my $driver = 'database driver';  # e.g., mysql or ODBC or ???
my $dbusername = 'domain\user.name';
my $dbpassword = 'password_here';
my $server     = 'server_name_here';
my $database   = 'Northwind';
my $q = new CGI;

print $q->header;
warningsToBrowser(1);

$dbh = DBI->connect("dbi:$driver:$database:$server", $dbusername, $dbpassword,
                        {'RaiseError' => 1, 'PrintError' => 1}
                     ) ||  die "$Error_Message $DBI::errstr";

$sth = $dbh->prepare('select * from employees');
$sth->execute() || die $sth->errstr;

while (my @cat1 = $sth->fetchrow_array ) {
   print "@cat1", "\n";
}

$dbh->disconnect();

 

by: FishMongerPosted on 2005-10-29 at 09:39:58ID: 15185505

Here's a little info on your 8001 error message.

8001: The Services DLL encountered an error while allocating memory
Memory could not be allocated. Verify that your system resources are not exhausted.


Here's a short script that will show what drivers and data sources you have available.

#!usr/bin/perl -w

  use DBI;

  @driver_names = DBI->available_drivers;
  @data_sources = DBI->data_sources('ODBC');
  print "Driver names: @driver_names",$/,$/;
  print $_,$/ for @data_sources;

 

by: billfinkriPosted on 2005-10-31 at 05:50:13ID: 15192490

FishMonger,

PERFECT!

Actually, your second script, which demonstrated which resources were available for me, is what did the the trick...!

Thus, I've discovered my problem - I'm NOT connecting to a "remote" host - I've only the LOCAL host Databases, using ODBC, to connect to. At least that's what the reported "Available Connections Were For Me."

What/If there is a syntax to connect to a 'remote' SQL Server ???

Thanks for your time, now that I've discovered the problem, just need to (correctly) connect to a remote SQL Server.

Any light you might be able to shed there?

Even so, I'll give the points here - you've given me enough to look in the right places, again. (Instead of WONDERING why I'm not connecting, now I know!)

 

by: billfinkriPosted on 2005-10-31 at 06:50:22ID: 15192918

FishMonger,

(Got IT!) Thanks for all of your time!

BTW - 'bout those lines I listed above ... there were a number of them, only through trial-error did I comment a few out, move a few around, just for testing.

Thus, I realized some of the code may have looked a bit odd.

Bill

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...