简体   繁体   English

(Perl)使用SQL :: Abstract创建DBI查询

[英](Perl) Create query for DBI with SQL::Abstract

I want to add new record to table1 on SQLite 我想在SQLite上向table1添加新记录

use SQL::Abstract;
my %data = (
  id => \'max(id)', # it is doesn't work so which variant is right?
  record => 'Something'
);

my $sql = SQL::Abstract->new;

my ($stmt, @bind) = $sql->insert('table1', \%data);


...
my $sth = $dbh->prepare($stmt);

If I used DBIx::Class in Catalyst app I would written like so: 如果我在Catalyst应用程序中使用DBIx :: Class,我会这样写:

id => $c->model('Model')->get_column('id')->max()

and it will work fine. 它将正常工作。 So how can I reach the same aim but using just SQL::Abstract which is used in DBIx::Class as well. 因此,如何仅使用SQL :: Abstract(也用于DBIx :: Class)来达到相同的目标。 Could someone fixed it? 有人可以修复它吗? Thanks. 谢谢。

This is a piece of code. 这是一段代码。 As you can see, first you need to get the max id+1 and then do the insert command. 如您所见,首先需要获取最大id + 1,然后执行insert命令。 I have to notice you this is not safe, because in a multi-(user,process,thread) environment, a second process can execute the same code and get race conditions. 我必须注意这是不安全的,因为在多(用户,进程,线程)环境中,第二个进程可以执行相同的代码并获得竞争条件。 But I assume you are just learning the SQL::Abstract api, and that problem doesn't matter 但是我假设您只是在学习SQL :: Abstract api,而这个问题并不重要

use DBI;
use SQL::Abstract;

#create table TEST(ID integer, NAME varchar);
my $dbh = DBI->connect('dbi:SQLite:dbname=test.db', '', '', {AutoCommit=>1});

my $sql = SQL::Abstract->new;

my($stmt, @bind) = $sql->select("TEST", [ 'max(ID)+1 as ID' ] );
my $sth = $dbh->prepare($stmt);
$sth->execute(@bind);

my ($id) = $sth->fetchrow_array // 1;

print "Select ID: $id", "\n";
$sth->finish;

($stmt, @bind) = $sql->insert("TEST", { ID=>$id, NAME=>"test-name"} );
$sth = $dbh->prepare($stmt);
$sth->execute(@bind);

$dbh->disconnect;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM