Update in Perl DBI not working, why? (full source posting, including DDL to create database in MySQL)

你。 提交于 2019-12-13 03:53:45

问题


Why is the UPDATE in "Example 2" not working?

#   MySQL DDL to create database used by code 
#
#   CREATE DATABASE sampledb;
#
#   USE sampledb;
#   
#   CREATE TABLE `dbtable` (
#     `id`  int(11) NOT NULL AUTO_INCREMENT,
#     `demo` longtext,
#     PRIMARY KEY  (`id`)
#   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# PERL MODULES WE WILL BE USING
use strict;
use warnings;
use DBI;

# CONFIG VARIABLES
my $platform = "mysql";
my $database = "sampledb";
my $host = "localhost";
my $port = "3306";
my $username = "root";
my $password = "password";

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

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

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

# Example 1 using prepare() and execute() INSERT

    # SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
    $id = 1;
    $demo = "test";

    # prepare() and execute() INSERT
    $query = "INSERT INTO dbtable (id, demo) VALUES ('$id', '$demo')";
    $query_handle = $connect->prepare($query);

    # EXECUTE THE INSERT
    $query_handle->execute();

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

    undef $query;

# Example 2 using do() UPDATE   

    # SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
    $id = 2;
    $demo = "test 2";

    # do() THE UPDATE
    $query = "UPDATE dbtable SET demo = '$demo' WHERE id = $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;

回答1:


You're trying to update a record with id=2, which doesn't seem to exist.




回答2:


Are you getting an error in $DBI::errstr? Aside from any output DBI might be giving you, the initial potential problem I see is that you insert a row with id=1, but your update is trying to update rows with id=2. There won't be any rows where id=2 to update.

A couple of other things you may also want to be aware of. Interpolating your variables right into your queries like that is bad practice and is what leads to SQL injection attacks. You should look at the DBI documentation on using placeholders for this. Placeholders also let you make the most effective use of prepare() when you need to do the same query on different values in a loop. If you just did that because it's just a quick test and you wouldn't do that in "real" code, then sorry for harassing you about it.

You also don't need to call prepare() before do(). do() handles the call to prepare() itself.



来源:https://stackoverflow.com/questions/5424107/update-in-perl-dbi-not-working-why-full-source-posting-including-ddl-to-crea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!