2012-09-12 118 views
0

名稱鍵值 。 。 。 。 。 。 用戶名進行更新Perl DBI mysql更新

#!/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. 

請協助

+3

如果你調用'做($查詢)'那麼你並不需要調用'準備($查詢)','做( )'在語句執行之前就準備好了。 –

+0

推薦'DBI-> connect($ dsn,$ u,$ p,{RaiseError => 1})' - 這會爲你帶來錯誤。例如,它會在你的(多餘的)'prepare()'中出現語法錯誤。 – pilcrow

回答

5

你的語法錯誤來自於一個事實,即「價值」是SQL的保留字。您需要報價該令牌時,它被用作一個標識符:

UPDATE jos_config SET `values` = ... 

一般情況下,MySQL的顯示的只是其中的語法錯誤是在查詢摘錄的開始,因爲它爲你做。

您的下一個問題是您沒有正確引用您與namekey比較的文字值,並且該文字值看起來像是標識符而不是MySQL的字符串。這裏的解決方案是忘記插變量和使用參數化查詢:

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

看起來你缺少周圍的namekey值的$ id一些引號:

$query = "UPDATE jos_config SET values = '$name' WHERE namekey = '$id';"; 
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); 
+1

這是一個問題,但這不是直接的問題。看到我的答案。 (另外,不需要'prepare()',不使用'$ query_handle'。) – pilcrow