The best way of catching errors in a DBI operation is through eval.
my $dbh = DBI->connect("dbi:driver:database",
"user","password",
{RaiseError=>1, PrintError=>0})
or die "can't connect ($DBI::errstr)\n";
my $sth;
eval {
$sth = $dbh->prepare( $sql );
$sth->execute;
};
if ($@) {
print "There was an error ($DBI::errstr)\n";
# do something appropriate
}
Notice that RaiseError must be on, to be sure it will raise an exception in case of error. The DBI docs have all the details of this procedure.
I believe you would benefit from a walk through our Tutorials about database programming. Start with this one.
As a side note, instead of using
"INSERT INTO t1 (lsname) VALUES ('$lsname')"; consider the placeholder mechanism, which will make sure that your field is properly quoted.
my $sql = "INSERT INTO t1 (lsname) VALUES ( ? )";
my $sth;
eval {
$sth = $dbh->prepare( $sql );
$sth->execute ($lsname);
};
if ($@) {
print "There was an error ($DBI::errstr)\n";
# do something appropriate
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|