user1249760
user1249760

Reputation: 153

perl DBI comma in query name

I am using perl to talk to an sqlite database, and am getting an error. I think it is because some of the chemical names (stored in the variable $drugs) have commas in them (they also have many other 'strange characters'.

Any help would be appreciated, thanks.

**error message:** 
- read in   57to find CIDs for
- Opened database successfully
- retrieving results for    cyclo(L-Val-L-Pro)
- retrieving results for    Sinapic_acid
- retrieving results for    NHQ
- DBD::SQLite::db prepare failed: near ",": syntax error at get_drugName2IDinfo.sqlite.pl line 33.
- DBD::SQLite::db prepare failed: near ",": syntax error at get_drugName2IDinfo.sqlite.pl line 33.

line 33:

my $stmt = qq(SELECT * from chem_aliases WHERE alias LIKE '$drug%');

example drug names:

(2R,3R,4S,6R)-2-((5-hydroxy-2,2-dimethyl-3,4-dihydro-2H-benzo[h]chromen-6-yl)oxy)-6-(hydroxymethyl)tetrahydro-2H-pyran-3,4,5-triol

partial script:

my %HoDrugs;
while (my $line=<IN>){
    chomp $line;
    $HoDrugs{$line}=1;
}
close(IN);
print "read in\t".scalar(keys %HoDrugs)."to find CIDs for\n";
##
my $driver   = "SQLite"; 
my $database = "/Users/alisonwaller/Documents/Typas/ext_data/STITCHv3.1/STITCHv3.1.sqlite.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) 
                  or die $DBI::errstr;

print "Opened database successfully\n";
###
my $outfile="$in_drugNms.sq.plsCIDs.tab";
open (OUT,">",$outfile);
foreach my $drug (keys %HoDrugs){

    my $stmt = qq(SELECT * from chem_aliases WHERE alias LIKE '$drug%');
    my $sth = $dbh->prepare( $stmt );
    my $rv = $sth->execute() or die $DBI::errstr;
    if($rv < 0){
            print $DBI::errstr;
    }
    while(my @row = $sth->fetchrow_array()) {
            print "retrieving results for\t$drug\n";                
            print OUT join("\t",$drug,$row[0],$row[1],$row[2]) . "\n";
    }
}
    print "Operation done successfully\n";
    $dbh->disconnect();

Upvotes: 0

Views: 233

Answers (2)

oalders
oalders

Reputation: 5279

Have you tried using placeholders rather than just quoting the string yourself?

my $sth = $dbh->prepare( 'SELECT * from chem_aliases WHERE alias LIKE ?' );
my $rv = $sth->execute( $drug . '%' ) or die $DBI::errstr;

Upvotes: 2

AgileDan
AgileDan

Reputation: 361

You could always try to use $drug =~ s/[[:punct:]]//g; before performing the query to try to remove punctuation characters?

If you don't want that, maybe replace them with spaces? $drug =~ s/,/ /g;

Upvotes: 0

Related Questions