Я получаю ошибку разбора при обновлении запроса через perl - PullRequest
0 голосов
/ 02 февраля 2019

Я попытался обновить таблицу в БД с помощью запроса на обновление в perl.Я получаю сообщение об ошибке ниже

SQL Error: couldnt update Server message number=20000 severity=0 state=0 line=0 server=AWSOSA1 text=ERROR=Parse failure on line 1 of statement 'UPDATE alerts.status SET AlertKey='Port 101 Circuit Up down' where Identifier='Link 101 Circuit Up Down Circuit Status Private Cloud uplinks CP0027829 DOWN 101 PC_SOCKET_PROBE', at or near '''

Я попытался напечатать запрос и запустить его в БД, и он работает там.Не уверен, почему возникает ошибка синтаксического анализа при выполнении сценария perl: - (

Кто-нибудь может помочь?

Ниже приведен запрос, который я пытался выполнить через perl:

UPDATE alerts.status SET AlertKey='Port 101 Circuit Up down' where Identifier='Link 101 Circuit Up Down Circuit Status Private Cloud uplinks CP0027829 DOWN 101 PC_SOCKET_PROBE'

Код:

my $sql1 = "SELECT AlertKey,AdditionalText,Identifier FROM alerts.status where AdditionalText like 'priority' AND Summary like 'Uplink' AND Type=1";
my $sth = $dbh->prepare($sql1);
my $alertkey;
my $str;
$sth->execute() || die "SQL Error: couldnt execute $DBI::errstr\n";

while(my @row = $sth->fetchrow_array())
{
        print "Inside while\n";
        my $str=$row[1];
        print "\nAdditional Text=".$str;
        $alertkey=$row[0];
        print "\nAlert Key before modification=".$alertkey;
        my $regex = qr/"link_index":"(\d+)"/mp;
        if($str =~ /$regex/g)
        {
                my $linkIndex=$1;
                $alertkey='Link '.$linkIndex.' Circuit Up down';
                print "\nAlertKey after modification=".$alertkey;
        }
        my $sql2 = "UPDATE alerts.status SET AlertKey='$alertkey' WHERE Identifier='$row[2]'";
        my $sth1 = $dbh->prepare($sql2);
        $sth1->execute() || die "SQL Error: couldnt update $DBI::errstr\n";;
        print "Number of rows updated :" + $sth->rows;
        $sth1->finish();
        $dbh->commit or die $DBI::errstr;
 }

$ dbh-> disconnect ();

1 Ответ

0 голосов
/ 02 февраля 2019

Как указано в комментариях, у вашего кода есть несколько проблем.Я не уверен, что следующее решит вашу проблему, но, по крайней мере, у него нет ни одной из упомянутых проблем.

Кстати: я сделал обоснованное предположение, основываясь на вашем регулярном выражении, что столбец AdditionalTextна самом деле содержит строку JSON.Тогда вам следует использовать анализатор JSON вместо применения регулярного выражения.

#!/usr/bin/perl
use strict;
use warnings;

use JSON qw(decode_json);

# DB setup etc.
use DBI....
my $dbh = ...
...

# Query for alert status
my $query_sth = $dbh->prepare(
    q(SELECT AlertKey,AdditionalText,Identifier FROM alerts.status where AdditionalText like 'priority' AND Summary like 'Uplink' AND Type=1)
);

# Update AlertKey
my $update_sth = $dbh->prepare(
    q(UPDATE alerts.status SET AlertKey=? WHERE Identifier=?)
);

# Execute query
$query_sth->execute()
    or die "SQL Error: couldn't execute $DBI::errstr\n";

# Loop over results
foreach my $row ($query_sth->fetchrow_arrayref) {
    my($key, $text, $id) = @{ $row };
    my $data;

    # Educated guess: $text is actually a JSON string
    eval {
        $data = decode_json($text);
    };
    if ($@) {
        # handle JSON parse errors here...
        next;
    }

    my $link = $data->{link_index};
    unless ($link) {
        # handle missing link index here...
        next;
    }

    # update alert key
    my $alert = "Port ${link} Circuit Up down";
    $update_sth->execute($alert, $id)
        or die "SQL Error: couldn't update $DBI::errstr\n";
}

Альтернатива без использования JSON

ПРИМЕЧАНИЕ: это не рекомендуется ,Если у вас есть JSON, XML, CSV, что угодно ...: всегда используйте парсер и работайте в "разобранном" домене.

    my($key, $text, $id) = @{ $row };

    # NOTE: regex might be incorrect if JSON property "link_index"
    #       is actually a number, not a string (see following line)
    my($link) = ($text =~ /"link_index":\s*"(\d+)"/;
    #         = ($text =~ /"link_index":\s*(\d+)/;
    unless ($link) {
        # handle missing link index here...
        next;
    }
...