mysql - 脚本仅在一个系统上给出数据库错误

标签 mysql database perl centos

我是一名 VOIP 管理员,我有用于更新 Perl 中的目录数据库的脚本,该脚本是在我受雇于此处之前从供应商处购买的。

该脚本在除一台服务器之外的所有服务器上都运行良好。

#!/usr/bin/perl
use lib "/opt/asterisk/lib/";
use DBI;
use Asterisk::config;
sub trim($);
# database information
$db="kesc";
$host="sip-ho.kesc.com.pk";
$userid="foo";
$passwd="bar";
$connectionInfo="dbi:mysql:$db;$host";
$hubname = "";

# make connection to database
$dbh = DBI->connect($connectionInfo,$userid,$passwd);
# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

my $rc = new Asterisk::config  (file=>'/etc/asterisk/sip.conf',keep_resource_array=>0);
@list = $rc->fetch_sections_list();
$n = 1;
foreach (@list)
{
    if ($_ ne "general") {

        $entry = $rc->fetch_keys_hashref(section=>$_);
        while ( my ($key, @value) = each(%$entry) )
        {
            if ($key eq "callerid") {
                @vars = split('<',$value[0][0]);
                $query = "insert into directory (extension,name,hub) values (" . trim($_) . ", '" . trim($vars[0]) . "', '$hubname') ON DUPLICATE KEY UPDATE hub='$hubname'";
                $sth = $dbh->prepare($query);
                $sth->execute();
            }
        }
    }
    $n++;
}

现在我在执行时遇到下面提到的错误。

DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Office', '') ON DUPLICATE KEY UPDATE hub=''' at line 1 at ./directory line 39.

我还用相同的 MySQL 版本从其他服务器替换了它,它运行得很好。

请指导我。

最佳答案

谢谢你的代码。正如我所怀疑的那样;你确实不应该将值直接插入到 SQL 语句中

将第 37、38 和 39 行更改为此,它应该适合您

$query = 'INSERT INTO directory (extension, name, hub) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE hub = ?';
$sth   = $dbh->prepare($query);
$sth->execute( trim($_), trim($vars[0]), $hubname, $hubname );

请注意,代码库中的其他地方可能存在相同的问题,因此确实应该对其进行彻底审查

关于mysql - 脚本仅在一个系统上给出数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46845041/

相关文章:

perl - 什么时候需要我们的关键字?

mysql - 删除带左连接的数据表

PHP MySQL - 按时差限制查询结果

.net - 数据库本地化 - 查找列表 - 更智能的方式

javascript - 使用来自数据库的选择选项

json - 使用perl解析json文件

php - 本地主机上的 MySQL 连接被拒绝

mysql - Over() 函数未按预期覆盖所有行

sql - 在 Vertica 数据库内全局创建倒排索引

linux - Perl 信号处理仅在ighandler 调用子例程时起作用一次