我想在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);
如果我在Catalyst应用程序中使用DBIx :: Class,我会这样写:
id => $c->model('Model')->get_column('id')->max()
它将正常工作。
因此,如何仅使用仅在DBIx :: Class中使用的SQL :: Abstract就可以达到相同的目标。
有人可以解决吗?谢谢。
最佳答案
这是一段代码。如您所见,首先需要获取最大id + 1,然后执行insert命令。我必须注意这是不安全的,因为在多(用户,进程,线程)环境中,第二个进程可以执行相同的代码并获得竞争条件。
但是我假设您只是在学习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;
关于sql - (Perl)使用SQL::Abstract为DBI创建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883667/