Perl DBI mysql更新

时间:2012-09-12 02:38:06

标签: mysql perl dbi

namekey值  。 。  。 。  。 。 要更新的用户名

#!/usr/bin/perl -w
# Use the DBI module

use  strict;
use warnings;
use DBI;

# CONFIG VARIABLES
my $platform = "mysql";
my $database = "prod";
my $host     = "localhost";
my $username = "root";
my $password = "admin";

# DATA SOURCE NAME
my $dsn = "dbi:$platform:$database:$host";

# PERL DBI CONNECT
my $connect = DBI->connect($dsn, $username, $password);

# VARS for Examples
my $query;
my $query_handle;
my $id;
my $demo;

# Example 2 using do() UPDATE   

# SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
$id   = "username";
$name = "Arty";

# do() THE UPDATE
$query        = "UPDATE jos_config SET values = '$name' WHERE namekey = $id;";
$query_handle = $connect->prepare($query);

# EXECUTE THE UPDATE
$query_handle = $connect->do($query);

print STDERR "ERROR: $DBI::errstr";
print STDERR "INFO: $query_handle rows updated";

undef $query;

错误消息:

DBD::mysql::db do 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 'values = 'Arty' WHERE namekey = smtp_username' at line 1 at /home/arty/Documents/SmtpDbchange2.pl line 40.
ERROR: 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 'values = 'Arty' WHERE namekey = smtp_username' at line 1Use of uninitialized value $query_handle in concatenation (.) or string at /home/arty/Documents/SmtpDbchange2.pl line 43.

请协助

4 个答案:

答案 0 :(得分:5)

您的语法错误来自“值”是SQL中的保留字。当它作为标识符时,您需要引用该标记:

UPDATE jos_config SET `values` = ...

通常,MySQL会向您显示查询摘录开头的语法错误,就像它为您所做的那样。

您的下一个问题是您没有正确引用与namekey比较的文字值,并且该文字值看起来像是一个标识符而不是MySQL的字符串。这里的解决方案是忘记插值变量并使用参数化查询:

$connect->do('UPDATE jos_config SET `values`=? WHERE namekey=?', undef, $name, $id);

答案 1 :(得分:0)

看起来你在namekey值$ id:

周围缺少一些引号
$query = "UPDATE jos_config SET values = '$name' WHERE namekey = '$id';";

答案 2 :(得分:0)

如果收到这样的错误,请打印出有问题的声明:

print $query;

显示:

UPDATE jos_config SET values = 'Arty' WHERE namekey = username;

然后盯着它,直到看到缺失的引号。

然后停止这样做并使用占位符:

$query = "UPDATE jos_config SET values=? WHERE namekey=?;";
$query_handle = $connect->prepare($query);
my $result = $connect->do($query, {}, $name, $id);

答案 3 :(得分:0)

你可以试试这个:

my $sthSetid = $dbh->prepare("UPDATE $table SET nameOfColumnToChange = ? WHERE id = ?");
$sthSetid->execute($newData, $refGetid[0]);
$sthSetid->finish;